/* Author: Datacom */
/* Global Variables -Start */
//http://refresh-sf.com/yui/#output
var panels;
var currIndex = 0;
var prev = 0;

function initMenu() {

    $('.accordion li .join-summary').css("display", "none");
    $('.accordion li .join-content').css("display", "none");
    $('.accordion li.completed .join-summary').not('.accordion li.selected .join-summary').slideDown();

    var currElement = $('.accordion li:first');
    var parent = currElement;


    $('.accordion li').each(function (i, l) {
        var parent = $(this);

        $(parent).find('.header').click(function () {
            if ($(parent).is('.selected')) {
                close(parent);
                return false;
            }

            if (currElement != null) {
                close(currElement);
            }
            $(parent).find(".join-content").slideDown();
            $(parent).addClass('selected');
            $(parent).find(".join-summary").slideUp();

            currElement = parent;
            return false;

        });
    });

    function close(element) {
        $(element).find(".join-content").slideUp();
        $(element).removeClass('selected');

        if ($(element).is('.completed')) {
            $(element).find(".join-summary").slideDown();
        }
    }

    /*
    $('.accordion li .header').click( function(){
    parent = $(this).parent().parent();
    $(parent).find(".join-summary").slideUp();
    $(parent).find(".join-content").slideDown();
    //$(currElement).find(".join-content .form-container").slideUp('normal');
    currElement = parent;
    return false;
    });
	
	
	
    $('.accordion li.completed .join-summary .header').click( function(){
		
    $(currElement).find(".join-content").slideUp('normal');
    $(currElement).find(".join-summary").slideDown('normal');
    $(parent).addClass("completed");
    $(currElement).removeClass("selected");
		
    parent = $(this).parent().parent();
		
    $(parent).find(".join-content .form-container").show();
    $(parent).find(".join-content").slideDown('normal');
    $(parent).find(".join-summary").slideUp('normal');
    $(parent).addClass("selected");
    currElement = parent;
		
    });
	
    $('.accordion li.completed .join-content .header').click( function(){
		
    var curr = $(this).parent().parent();
		
    $(curr).find(".join-content .form-container").show();
    $(curr).find(".join-content").slideUp('normal');
    $(curr).find(".join-summary").slideDown('normal');
    $(curr).addClass("selected");
    });*/

}

function openSharePage() {
    var path = 'http://' + document.location.host + '/Sign-up/Share.aspx?param=' + getUrlParameter('param');
    window.open(path);
}

function getSharePath() {
    return path = 'http://' + document.location.host + '/Sign-up/Share.aspx?param=' + getUrlParameter('param');
}

function getUrlParameter(name) {

    var q = document.URL.split('?')[1];
    if (q != undefined) {
        q = q.split('&');
        for (var i = 0; i < q.length; i++) {
            var param = q[i].split('=');
            if (param[0] = name) {
                return param[1];
            }
        }
    }

    return "";
}

function initCampaign() {
    panels = $('.campaign .panel');
    panels.each(function (index) {
        $(this).css({ opacity: (index == 0) ? 1 : 0 });
    });
    $(".campaign .controls li").each(function (i, l) {
        $(this).click(function (e) {
            if (currIndex != i) {
                currIndex = i;
                swapImages();
                $('.campaign .controls li').removeClass('selected');
                $(this).addClass('selected');
            }
            e.preventDefault();
        });
    });
    $('.panel1').addClass('panel-selected');
}




function swapImages() {
    if (currIndex > panels.length - 1) {
        currIndex = 0;
    }
    $(panels[currIndex]).addClass('panel-selected');
    $(panels[prev]).animate({ opacity: 0 });
    $(panels[currIndex]).animate({ opacity: 1 });
    $(panels[prev]).removeClass('panel-selected');
    prev = currIndex;
}

/*usage plugin for energy plans*/
(function ($) {
    jQuery.fn.usageItemPlugin = function () {

        var usageItems = $(this);
        var button;
        var time = 300;
        var currentItem;

        $(usageItems).each(function (i, l) {
            if ($(this).hasClass('selected')) { return; }

            $(this).click(function (e) {
                if (currentItem != null) { reset(currentItem); }

                $(this).removeClass("simple-gray-gradient-with-border-lighter");
                $(this).removeClass("color-change");
                $(this).addClass("simple-blue-gradient-with-border selected");
                currentItem = $(this);
				if($(this).hasClass('step-one')) {
					_gaq.push(['_trackPageview', '/Sign-Up/Select-Usage/']);
				} else if($(this).hasClass('step-two')) {
					_gaq.push(['_trackPageview', '/Sign-Up/Select-A-Plan/']);
				}	
                return false;
            });

            $(this).hover(
				function () {
                    if ($(this).hasClass('selected')) { return; }
				        $(this).addClass("simple-orange-gradient-with-border color-change");
				        $(this).removeClass("simple-gray-gradient-with-border-lighter");
				        button = $(this).find(".button");
				        $(button).animate({ right: "-16px" }, time);
				},
			  	function () {
			  	    if ($(this).hasClass('selected')) { return; }
			  	    $(this).removeClass("simple-orange-gradient-with-border color-change");
			  	    $(this).addClass("simple-gray-gradient-with-border-lighter");
			  	    $(button).animate({ right: "0px" }, time);
			  	}
			);
        });

        function reset(item) {
            var items = $(item).parent().find(".usage");
            $(items).each(function (i, l) {
                if ($(this).hasClass('selected')) {
                    $(this).addClass("simple-gray-gradient-with-border-lighter");
                    $(this).removeClass("simple-blue-gradient-with-border selected");
                    $(this).find(".button").animate({ right: "0px" }, time);
                    return;
                }
            });
        }
    }


})(jQuery);


/*Light box plugin*/
(function ($) {
    jQuery.fn.showLightBox = function (id) {

        var lightBoxbtn = $(this);
        var lightBoxContainer = $(id + ' .light-box').find('.light-box-container');
        var lightBoxContent;

        $(lightBoxbtn).click(function () {
            
            if($('#iframe1').attr('src') == null)
            {
                $('#iframe1').attr('src','http://mercury.custhelp.com/app/feedback');
            }

            $(id + ' .light-box').fadeIn();
            document.documentElement.style.overflow = 'hidden';
            return false;
        });

        $(id + ' .light-box .close-but').click(function () {
            $(id + ' .light-box').fadeOut();

            document.documentElement.style.overflow = 'auto';
            return false;

        });

    }
})(jQuery);


/*combo box plugin*/
(function ($) {
    jQuery.fn.comboBoxPlubin = function (textBoxID,doPostBack) {
         var selectedItem;
        var comboBoxRoot = $(this);
       
        var header = $(this).find(".combo-box-header");

        var items = $(comboBoxRoot).find("ul li");
        
        $(items).each(function (i, l) {
           if($(this).find(".input-label").text() == $(textBoxID).val())
           {
                selectedItem = $(this);
                $(selectedItem).addClass("selected");
                $(textBoxID).val($(this).find(".input-label").text());
           } 
        });

        $(header).html($(selectedItem).find(".input-label").text());
        $(header).unbind('click');
         $(header).click(function () {
            // IE7 Issue fix
            $(comboBoxRoot).removeClass("fix-relative-issue");
            $($(comboBoxRoot).find("ul")).slideToggle("fast");
        });
        

        $(items).each(function (i, l) {
            $(this).click(function () {
                
                $(selectedItem).removeClass("selected");
                $(this).find("input").attr("checked", "true");
                $(header).html($(this).find(".input-label").text());
                $(textBoxID).val($(this).find(".input-label").text());
                // IE7 Issue fix
                $(comboBoxRoot).addClass("fix-relative-issue");
                $(this).parent().slideUp("fast");
                selectedItem = $(this);
                $(selectedItem).addClass("selected");
                disableJoinButton();
                
            });
        });
    }
})(jQuery);

function callWebService()
{
    var pathname = window.location.pathname;
   
        $.ajax({
      type: "POST",
      url: "/TestWebService.asmx/getTheRegions",
      contentType: "text/xml; charset=utf-8",
      dataType: "xml",
      success: function(json) { 

      },
      error: function(e){
        }
    });


    $("#suburbUL li.default").after("<li>hello</li>");
}

function initChatWindow() {
    $('.chat-btn').click(function (e) {
        $(this).animate({ right: "-100px", bottom: "-100px" }, 300, function () {
            $('.chat-container').animate({ bottom: "0px" }, 300);

        });
        return false;
    });

    $('.chat-header .chat-close-but').click(function (e) {
        $('.chat-container').animate({ bottom: "-500px" }, 300, function () {
            $('.chat-btn').animate({ right: "0px", bottom: "0px" }, 300);
        });
        $('.chat-container .init-screen').slideDown();
        $('.chat-container .chat-screen').slideUp();
        return false;
    });

    $('.chat-container .submit-btn').click(function (e) {
        $('.chat-container .init-screen').slideUp();
        $('.chat-container .chat-screen').slideDown();
        return false;
    });

}


$(document).ready(function () {

    //initMenu();
    initCampaign();
    initFeedback();
    //initNavTest();
    initLightBoxModalPopUp();
    $('span.step-two').usageItemPlugin();
    $('span.step-one').usageItemPlugin();

  //  $("#JFComboBox").comboBoxPlubin();
    // $("#JFComboxBox").comboBoxPlubin();

    showHideHero();
    simulateJoinPlan();


});
/************************  [ Modal Pop Up Logic - Start ] ********************/
function initLightBoxModalPopUp() {

    var header = "";
    var body = "";
    $('.light-box-content-no-style').click(function () {

        var urlCheck = $(genericLightBoxId + ' .light-box-header span').data('href');
        if (urlCheck == null || urlCheck != $(this).attr('href')) {
            $(genericLightBoxId + ' .light-box-header span').html('');
            $(genericLightBoxId + ' .light-box-content .form-container').html('');
            $.get($(this).attr('href'), function (result) {

                $(genericLightBoxId + ' .light-box-header span').html($(result).find("#spanheaderForLB").html())
                $(genericLightBoxId + ' .light-box-content .form-container').html($(result).find("#formContainerForLB").html());

            });
            $(genericLightBoxId + ' .light-box-header span').data('href', $(this).attr('href'));
        }
        else {
            // alert("Debug::request is not being made again for the same content");
        }

        /*Alternate solution based on the jquery load*/
        // $('.light-box-header span').load($(this).attr('href') + ' #spanheaderForLB');
        // $('.light-box-content .form-container').load($(this).attr('href') + ' #formContainerForLB');
        return false;
    });

    $('.light-box-content-no-style').showLightBox(genericLightBoxId);

}
function modal_btnClose_Click_Client() {

    lightBoxFadeOut(genericLightBoxId);
    return true;

}

/************************  [ Modal Pop Up Logic - End ] ********************/

/************************* [Onload Global Function - Start] *****************************************/
function onLoadDynamicValidation() 
{
//    if ($.isFunction(window.pageLoadFeedback)) {
//        pageLoadFeedback();
//    }
    if ($.isFunction(window.pageLoadJoinForm)) {
        pageLoadJoinForm();
    }
    if ($.isFunction(window.pageLoadFromPlans)) {
        pageLoadFromPlans() 
    }
}
function pageLoad(sender, args) 
{
    $(document).ready(function () {
       
        onLoadDynamicValidation();

    });
}
/************************** [Onload Function - End] *****************************************/


/************************  [ Generic form  methods - Start] ********************/

function lightBoxFadeOut(id) {
    $(feedBackLightBoxId + ' .light-box').fadeOut();
    document.documentElement.style.overflow = 'visible';
    
}


function ClearInput(value, id, onblur) {

    var input = document.getElementById(id);
    if (value == input.value) {

        if (onblur == 'True') {
            input.value = value;
        }
        else {
            input.value = '';
        }


    }
    else if (input.value == '') {
        input.value = value;
    }
  

}

function genericEmailValidation(val) {

    var emailReg = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
    return emailReg.test(value);
}

function genericHtmlInjectionCheck(value) {

    var testForCharacters = (value.indexOf("<") > -1 || value.indexOf(">") > -1);
    var vRx = new RegExp("<(.|\n)+?>", "ig");
    return !vRx.test(value) && !testForCharacters;
}

function genericValidationHelper(source, args, extensionFilter, errorMsgFilter, elementID, checkString, fetchControlID) {
    var cntrl_id = source;
    if (fetchControlID) {
        cntrl_id = $(source).attr("controltovalidate");
    }
    var cntrl = $("#" + cntrl_id + extensionFilter);


    if ($(cntrl).val()) {
        var is_valid = ($(cntrl).val() != checkString) && genericHtmlInjectionCheck($(cntrl).val());
        is_valid ? $('#' + elementID).removeClass("field-row-error") : $('#' + elementID).addClass("field-row-error");
        !is_valid ? $('#' + elementID + ' .error-msg' + errorMsgFilter).css("display", "block") : $('#' + elementID + ' .error-msg' + errorMsgFilter).css("display", "none");
        args.IsValid = is_valid;

    }
    else {
        $('#' + elementID).addClass("field-row-error");
        $('#' + elementID + ' .error-msg' + errorMsgFilter).css("display", "block");
        is_valid = false;
        args.IsValid = false;

    }
    return is_valid;
}


// of (D)D/(M)M/(YY)YY and returns true/false
function isValidDate(s) {
    // format D(D)/M(M)/(YY)YY
    var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;

    if (dateFormat.test(s)) {
        // remove any leading zeros from date values
        s = s.replace(/0*(\d*)/gi, "$1");
        var dateArray = s.split(/[\.|\/|-]/);

        // correct month value
        dateArray[1] = dateArray[1] - 1;

        // correct year value
        if (dateArray[2].length < 4) {
            // correct year value
            dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
        }

        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
        if (testDate.getDate() != dateArray[0] || testDate.getMonth() != dateArray[1] || testDate.getFullYear() != dateArray[2]) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function activeClientSideValidation(valgroup, enable) {
    $.each(Page_Validators, function (index, validator) {
        if (validator.validationGroup == valgroup) {
            ValidatorEnable(validator, enable);
        }
    });
}
function activateDisableValidation(id,value) 
{
    if (id == "JFAboutYouPanel") {
        activeClientSideValidation("aboutYouValidation", value); 
    }
    else if (id == "JFAboutTheProperty") {
        activeClientSideValidation("aboutPropValidation", value); 
    }
    else if (id == "JFAboutYourHome") {
        activeClientSideValidation("aboutHomeValidation", value);
    }
   /* else if (id = "plc_lt_feedBackLightBox_upnlAboutYou")
    {
        activeClientSideValidation("firstNameLastName", value);
    }
    else
    {
        activeClientSideValidation("feedbackpanelvalidation", value);
    }*/

}

function validationValidateControlOnly(valgroup, controlID) 
{
    $.each(Page_Validators, function (index, validator) {
        if (validator.validationGroup == valgroup && $(validator).attr("controltovalidate").indexOf(controlID) > -1) {
            if ($(validator)[0].enabled) {
                ValidatorValidate(validator);
            }
        }
    });
}

function Page_ClientValidate_Trigger(id,elemID) {
    if (id == "JFAboutYouPanel") {

        //  Page_ClientValidate("aboutYouValidation");
        validationValidateControlOnly("aboutYouValidation", elemID); 
    }
    else if (id == "JFAboutTheProperty") {
        //  Page_ClientValidate("aboutPropValidation");
        validationValidateControlOnly("aboutPropValidation", elemID); 
    }
    else if (id == "JFAboutYourHome") {
        //  Page_ClientValidate("aboutHomeValidation");
        validationValidateControlOnly("aboutHomeValidation", elemID); 
    }
}

function onkeyUpFix(id) 
{
    activateDisableValidation(id, true);
    var parent = $("#" + id);
  //  if ($(parent).hasClass('error')) {
    $("#" + id + " input[type=text]").each(function (i, l) {
        $(this).keydown(function (event) {
            $(this).attr('autocomplete', 'off');


        });
    }).keyup(function (event) { Page_ClientValidate_Trigger(id, $(this).attr("id")); $(this).attr('autocomplete', 'on'); disableJoinButton(); });


   // }
}

function onMouseDownGetFocus(id) 
{
    var parent = $("#" + id);
    if ($(parent).hasClass('error')) {
        $("#" + id + " input[type=text]").each(function (i, l) {
            $(this).mousedown(function (event) {
                activateDisableValidation(id, false);
                $(this).attr('autocomplete', 'off');
                $(this).focus();
            });
        }).mouseup(function (event) { setTimeout(activateDisableValidation(id, true), 500); $(this).attr('autocomplete', 'on'); });

        $("#" + id + " input[type=radio]").each(function (i, l) {
            $(this).mousedown(function (event) {
                $(this).attr('checked', 'checked');
                $(this).focus();
            });
        });

        $("#" + id + " input[type=checkbox]").each(function (i, l) {
            $(this).mousedown(function (event) {
                $(this).attr('checked', 'checked');
                $(this).focus();
            });
        });

        $("#" + id + " label").each(function (i, l) {
            $(this).mousedown(function (event) {
                var labelid = $(this).attr('for');
                $('#' + labelid).trigger('click');
                $('#' + labelid).focus();
            });
        });
    }
}

function clickOnKeyUpChangeBinding(id) {
    var parent = $("#" + id);
    if ($(parent).hasClass('completed')) {
        $("#" + id + " input[type=text]").each(function (i, l) {
            $(this).keyup(function (event) {
                parent.addClass("dirty");
                disableJoinButton();
            });

        });
        $("#" + id + " input[type=checkbox]").each(function (i, l) {
            $(this).click(function (event) {
                parent.addClass("dirty");
                disableJoinButton();
            });
        });
        $("#" + id + " input[type=radio]").each(function (i, l) {
            $(this).click(function (event) {
                parent.addClass("dirty");
                disableJoinButton();
            });
        });
    }
}
function checkIfDateIsOlderThanXMonths(usrDate, curDate, threshold) {
    var usrYear, usrMonth = usrDate.getMonth() + 1;
    var curYear, curMonth = curDate.getMonth() + 1;
    if ((usrYear = usrDate.getFullYear()) < (curYear = curDate.getFullYear())) {
        curMonth += (curYear - usrYear) * 12;
    }
    var diffMonths = curMonth - usrMonth;
    if (usrDate.getDate() > curDate.getDate())
        diffMonths--;
    if (diffMonths < threshold) {
        return false;
    }
    else {
        return true;
    }
}

function checkIfDateUptoXDaysInTheFuture(usrDate, curDate, threshold) {
    var intMilDay = 24 * 60 * 60 * 1000;
    var intMilDif = usrDate - curDate;
    var intDays = Math.floor(intMilDif / intMilDay);
    if (intDays < threshold) {
        return false;
    }
    else {
        return true;
    }
}

function stripHtml(value) 
{
    return value.replace(/<\/?[^>]+>/gi, '');

}

/************************  [ Generic form  methods - End] ********************/

/************************ [ Join Form Methods - Start ] ********************/

    /*About You Methods - Start*/
        function JFValidationAboutYouFirstNameTextBox(source,args) 
        {

            var temp1 = genericValidationHelper(source, args, "", ":nth-child(1)", "JFAboutYouYourName", JFFirstNameDefaultContent, true);
            var temp2 = genericValidationHelper(JFAboutYouLastName, args, "", ":nth-child(2)", "JFAboutYouYourName", JFLastNameDefaultContent, false);
            args.IsValid = temp1 && temp2;
            if (!args.IsValid) {
                $('#' + 'JFAboutYouYourName').addClass("field-row-error");
            }
            
            return args.IsValid;

        }

        function JFValidationAboutYouLastNameTextBox(source, args) {


            var temp1 = genericValidationHelper(source, args, "", ":nth-child(2)", "JFAboutYouYourName", JFLastNameDefaultContent, true);
            var temp2 = genericValidationHelper(JFAboutYouFirstName, args, "", ":nth-child(1)", "JFAboutYouYourName", JFFirstNameDefaultContent, false);
            args.IsValid = temp1 && temp2;
            if (!args.IsValid) {
                $('#' + 'JFAboutYouYourName').addClass("field-row-error");
            }
            
            return args.IsValid;
        }

        function JFValidationAboutYouGender(source, args) 
        {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFAboutYouRadioBtn", "", true);
            return args.IsValid;
        }


        function JFValidationAboutDOB(source,args) 
        {
            var age = 18;
            var invalidAge = false;
            genericValidationHelper(JFDOBDays, args, "", ":nth-child(1)", "JFAboutyouDOB", JFDOBDaysDefaultContent, false);
            genericValidationHelper(JFDOBMonths, args, "", ":nth-child(1)", "JFAboutyouDOB", JFDOBMonthsDefaultContent, false);
            genericValidationHelper(JFDOBYears, args, "", ":nth-child(1)", "JFAboutyouDOB", JFDOBYearsDefaultContent, false);

            var date = "";
            if (args.IsValid)
            {
                var day = $("#" + JFDOBDays).val();
                var month = $("#" + JFDOBMonths).val();
                var year = $("#" + JFDOBYears).val();
                var checkDay = day.length <= 2 && day.length >= 1 && !isNaN(day);
                var checkMonth =  month.length<=2 && month.length>=1 && !isNaN(month);
                var checkYear = year.length == 4 && !isNaN(year);

                if (checkDay && checkMonth && checkYear) 
                {
                    date = day + "/" + month + "/" + year;
                    args.IsValid = isValidDate(date);
                    if (args.IsValid) {
                        var dt = new Date(year, month - 1, day);
                        var today = new Date();
                        years = today.getFullYear() - dt.getFullYear();
                        if (today.getMonth() < dt.getMonth() || (today.getMonth() == dt.getMonth() && today.getDay() < dt.getDay())) {
                            years = years - 1;
                        }
                        args.IsValid = years >= age;
                        invalidAge = !args.IsValid;
                    }
                }
                else 
                {
                    args.IsValid = false;
                }

            }
            if (!args.IsValid)
            {
                $('#' + 'JFAboutyouDOB').addClass("field-row-error");
                if (invalidAge) {
                    $('#' + 'JFAboutyouDOB' + ' .error-msg:nth-child(2)').css("display", "block");
                    $('#' + 'JFAboutyouDOB' + ' .error-msg:nth-child(1)').css("display", "none");
                }
                else {
                    $('#' + 'JFAboutyouDOB' + ' .error-msg:nth-child(2)').css("display", "none");
                    $('#' + 'JFAboutyouDOB' + ' .error-msg:nth-child(1)').css("display", "block");
                }
            }
            return args.IsValid;
        }

        function JFValidationAboutYouEmailAddress(source, args) 
        {
            genericValidationHelper(source, args, "", "", "JFAboutYouEmail", JFEmailDefaultContent, true);
            if (args.IsValid) {
                var cntrl_id = $(source).attr("controltovalidate");
                var cntrl = $("#" + cntrl_id + "");
                var value = $(cntrl).val();
                var emailReg = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
                args.IsValid = emailReg.test(value);
            };
            if (!args.IsValid) {
                $('#' + 'JFAboutYouEmail').addClass("field-row-error");
                $('#' + 'JFAboutYouEmail' + ' .error-msg').css("display", "block");
            }
            return args.IsValid;
        }

        function JFValidationAboutYouNumber(source, args) 
        {
            genericValidationHelper(source, args, "", "", "JFAboutYouNumber", JFNumberDefaultContent, true);
            return args.IsValid;
        }
        /*About You Methods - End*/

        /*About your property - Start*/

        function JFValidationRentOrOwn(source, args) 
        {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFRentOrOwn", "", true);
            return args.IsValid;
        }
        function JFValidationPrimaryResidence(source, args) {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFPrimaryProperty", "", true);
            if (args.IsValid && planUsage == 1) {
                var cntrl_id = $(source).attr("controltovalidate");
                var cntrl = $("#" + cntrl_id + " input[type='radio']:checked");
                var residenceValue = $(cntrl).val();

                args.IsValid = args.IsValid && (residenceValue.indexOf('Yes') > -1);

                if (!args.IsValid) {
                    $('#' + 'JFPrimaryProperty').addClass("field-row-error");
                    $('#' + 'JFPrimaryProperty' + ' .error-msg:nth-child(2)').css("display", "block");
                }
            }
            else {
                $('#' + 'JFPrimaryProperty' + ' .error-msg:nth-child(2)').css("display", "none");
            }
            
            return args.IsValid;
        }
        function JFValidationMovingInOrChanging(source, args) {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFMovingInOrChanging", "", true);
            return args.IsValid;
        }
        function JFValidationMovingInDate(source, args) {
            genericValidationHelper(source, args, "", "", "JFMovingInDate", JFMovingDateDefaultContent, true);
            if (args.IsValid)
            {
                var cntrl_id = $(source).attr("controltovalidate");
                var cntrl = $("#" + cntrl_id + "");
                var datevalue = $(cntrl).val();
                var array = datevalue.split('/');
                var date = new Date(array[2], array[1] - 1, array[0]);
                var currentDate = new Date();
                args.IsValid = !checkIfDateIsOlderThanXMonths(date, currentDate, movingInMonths) && !checkIfDateUptoXDaysInTheFuture(date, currentDate, movingInDays);
            }
            if (!args.IsValid)
            {
                $('#' + 'JFMovingInDate').addClass("field-row-error");
                $('#' + 'JFMovingInDate' + ' .error-msg').css("display", "block");
            }
            return args.IsValid;
        }

        function JFValidationMovingInPreviousAddressTime(source, args) 
        {
            args.IsValid = genericValidationHelper(JFMoveInDateYears, args, "", "", "JFMovingDateExtension", JFMovingInPropertyPreviousYear, false) && genericValidationHelper(JFMoveInDateMonths, args, "", "", "JFMovingDateExtension", JFMovingInPropertyPreviousMonth, false);
            if (args.IsValid) {
                var years = $("#" + JFMoveInDateYears).val();
                var months = $("#" + JFMoveInDateMonths).val();

                args.IsValid = !isNaN(years) && !isNaN(months) && months <= 11;
                args.IsValid = args.IsValid && years >= 0 && months >= 0;
                if (!args.IsValid) {
                    $('#JFMovingDateExtension').addClass("field-row-error");
                    $('#JFMovingDateExtension .error-msg').css("display", "block");
                }
            }
            return args.IsValid;

        }

        function JFValidationPreviousAddressTime(source, args) {
          args.IsValid = genericValidationHelper(JFMoveInYears, args, "", "", "JFPropYearandMonths", JFPropertyLivedDefaultContentYear, false) && genericValidationHelper(JFMoveInMonths, args, "", "", "JFPropYearandMonths", JFPropertyLivedDefaultContentMonth, false);

          if (args.IsValid)
          { 
            var years = $("#"+JFMoveInYears).val();
            var months = $("#" + JFMoveInMonths).val();

            args.IsValid = !isNaN(years) && !isNaN(months) && months <= 11;
            args.IsValid = args.IsValid && years >= 0 && months >= 0;
            if (!args.IsValid)
            {
                $('#JFPropYearandMonths').addClass("field-row-error");
                $('#JFPropYearandMonths .error-msg').css("display", "block");
            }
          }
          return args.IsValid;
      }



        /*Changing Address */
        function JFValidatonTextBoxAutoComplete(source, args)
        {
            args.IsValid =  genericValidationHelper(source, args, "", "", "JFAutoCompleteAddress", JFChangeAddressAddressContent, true);
            return args.IsValid;
        }

        function streetNumberValidation(address,defaultContent,elemID) {
            var valid = (address == "") || (address.indexOf(defaultContent) > -1) || !isNaN(address);
            if (!valid) {
                $('#'+elemID).addClass("field-row-error");
                $('#'+elemID +' .error-msg').css("display", "block");
            }
            else {
                $('#'+elemID).removeClass("field-row-error");
                $('#'+elemID +' .error-msg').css("display", "none");
            }
            return valid;
        }
        function alphaValidation(alpha,defaultContent,elemID) {
            var letterReg = /^[a-zA-Z]$/gi;
            var onlyLetters = letterReg.test(alpha);
            var valid = (alpha == "") || (alpha.indexOf(defaultContent) > -1) || onlyLetters;
            if (!valid) {
                $('#'+elemID).addClass("field-row-error");
                $('#'+elemID +' .error-msg').css("display", "block");
            }
            else {
                $('#'+elemID).removeClass("field-row-error");
                $('#'+elemID +' .error-msg').css("display", "none");
            }
            return valid;
        }

        function JFValidatonTextBoxStreetNumber(source, args) {
            var cntrl_id = $(source).attr("controltovalidate");
            var cntrl = $("#" + cntrl_id + "");
            var address = $(cntrl).val();
            var alpha = $("#" + JFAlpha).val();
            var invalidHtmlInputs = genericHtmlInjectionCheck(address) && genericHtmlInjectionCheck(alpha);
            args.IsValid = streetNumberValidation(address,JFChangeAddressStreetNumberContent,"JFChangeAddressUnit") && alphaValidation(alpha,JFChangeAddressAlpha,"JFChangeAddressUnit") && invalidHtmlInputs;
            return args.IsValid;
        }
        function JFValidatonTextBoxAlpha(source, args) {
            var cntrl_id = $(source).attr("controltovalidate");
            var cntrl = $("#" + cntrl_id + "");
            var alpha = $(cntrl).val();
            var address = $("#" + JFStreetNumber).val();
            var invalidHtmlInputs = genericHtmlInjectionCheck(address) && genericHtmlInjectionCheck(alpha);
            args.IsValid = streetNumberValidation(address,JFChangeAddressStreetNumberContent,"JFChangeAddressUnit") && alphaValidation(alpha,JFChangeAddressAlpha,"JFChangeAddressUnit")  && invalidHtmlInputs;
            return args.IsValid;
        }
        function JFValidatonTextBoxRegionValue(source, args) {

            args.IsValid = genericValidationHelper(source, args, "", "", "JFChangeRegionSuburb", JFChangeAddressRegion, true);
            return args.IsValid;

        }

        function JFValidatonTextBoxCountry(source, args) {
            args.IsValid = genericValidationHelper(source, args, "", "", "JFChangeCountry", JFChangeAddressCountry, true);
            return args.IsValid;
        }
       


        /*About your property - End */

        /*About your Home -start */
        function JFValidationPower(source, args) 
        {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFPower", "", true);
            return args.IsValid;
        }
        function JFValidationGas(source, args) {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFGas", "", true);
            return args.IsValid;
        }
        function JFValidationDog(source, args) {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFDog", "", true);
            return args.IsValid;
        }
        function JFValidationMedical(source, args) {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFMedical", "", true);
            return args.IsValid;
        }
        function JFValidationVunerable(source, args) {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFVunerable", "", true);
            return args.IsValid;
        }
        function JFValidationFinancial(source, args) {
            genericValidationHelper(source, args, " input[type='radio']:checked", "", "JFFinancial", "", true);
            return args.IsValid;
        }
        /*About your Home -end */

        /*T&C and Join Button - Start*/

        function JFValidationCheckBox(source, args) 
        {
            var cntrl_id = $(source).attr("controltovalidate");
            args.IsValid = $('#' + cntrl_id).attr('checked');
            return args.IsValid;
        }
        function clientClickJoin() 
        {
            var val = validateAndEnableJoinButton();
            if (val == 0) {
                return false;
            }
            else 
            {
                Page_ClientValidate("aboutYouValidation");
                Page_ClientValidate("aboutPropValidation");
                Page_ClientValidate("aboutHomeValidation");
            }
            return val;
        }
        function checkClientSideValidation(valgroup) {
            var valid = true;
            var count =0;
            $.each(Page_Validators, function (index, validator) {
                if (validator.validationGroup == valgroup) {
                    if (validator.enabled) {
                        valid = valid && validator.isvalid;
                        count = 1;
                    }
                }
            });
            if (count == 0) {
                valid = false;
            }
            return valid;
        }

        function disableJoinButton() {
            $("#" + JFJoinButton).fadeTo(1, 0.2);
            $("#" + JFJoinButton).data("enabledForSubmit", false);
        }
        function enableJoinButton(bool) {

            var valid = bool;
            valid = valid && $('#' + JFTCCheck).attr('checked') && $('#' + JFAcceptCC).attr('checked');
            $('.accordion li').each(function (i, l) {
                if ($(this).hasClass("dirty")) {
                    valid = valid && false;
                    return false;
                }
            });
            if (valid) {
                //  $("#" + JFJoinButton).disable = false;
                $("#" + JFJoinButton).fadeTo(1, 1.0);
                $("#" + JFJoinButton).data("enabledForSubmit", true);
            }
            else {
                disableJoinButton();
            }


        }
        
        /*T&C and Join Button - End*/

       
/************************ [ Join Form Methods - End ] ********************/

/************************  [ Feedback form button methods - Start ] ********************/
var feedBackActive = false;
function initFeedback() {

    $('.feedback-btn').click(function () {
        return false;
    });
   
    $('.feedback-btn').showLightBox(feedBackLightBoxId);

}

function validateFeedbackForm(source, args) {

    genericValidationHelper(source, args, " input[type='radio']:checked", "", 'feedbackRadioBtn', "", true);
    return args.IsValid;


}

function validateFeedbackFormTextBox(source, args) {
    genericValidationHelper(source, args, "", "", 'feedbackTextHolder', "", true);
    return args.IsValid;
}


function validationAboutYouFirstNameTextBox(source, args) {

    var temp1 = genericValidationHelper(source, args, "", ":nth-child(1)", "firstLastName", firstNameDefaultContent, true);
    var temp2 = genericValidationHelper(aboutYouLastName, args, "", ":nth-child(2)", "firstLastName", lastNameDefaultContent, false);
    args.IsValid = temp1 && temp2;
    if (!args.IsValid) {
        $('#' + 'firstLastName').addClass("field-row-error");
    }
   
    return args.IsValid;


}

function validationAboutYouLastNameTextBox(source, args) {

    var temp1 = genericValidationHelper(source, args, "", ":nth-child(2)", "firstLastName", lastNameDefaultContent, true);
    var temp2 = genericValidationHelper(aboutYouFirstName, args, "", ":nth-child(1)", "firstLastName", firstNameDefaultContent, false);
    args.IsValid = temp1 && temp2;
    if (!args.IsValid) {
        $('#' + 'firstLastName').addClass("field-row-error");
    }

    return args.IsValid;
}

function validationAboutYouEmailTextBox(source, args) {

    genericValidationHelper(source, args, "", "", "aboutyouemail", emailDefaultContent, true);
    if (args.IsValid) {
        var cntrl_id = $(source).attr("controltovalidate");
        var cntrl = $("#" + cntrl_id + "");
        var value = $(cntrl).val();
        var emailReg = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
        args.IsValid = emailReg.test(value);
    };
    if (!args.IsValid) {
        $('#' + 'aboutyouemail').addClass("field-row-error");
        $('#' + 'aboutyouemail' + ' .error-msg').css("display", "block");
    }
    return args.IsValid;

}


function comboBoxActivate() {
    $($(".combo-box-container").find("ul")).slideToggle("fast");
    return false;
}


function setComboBoxSelection(control) {

    var root = $(".combo-box-container");
    var items = $(root).find("ul li");
    var header = $(root).find(".combo-box-header");

    $(items).each(function (i, l) {
        $(this).removeClass("selected");
    });

    var liSelected = $("#" + control.id).find("li");

    $(header).html($(liSelected).find(".input-label").text());

    $($(root).find("ul")).slideToggle("fast");

    return false;

}

function btnCloseTimer() {
    btnClose_Click_Client();
    _doPostBack('plc$lt$feedBackLightBox$CloseBtn', '');
}



function btnClose_Click_Client() {
   
    lightBoxFadeOut(feedBackLightBoxId);
    return true;
}

/************************  [ Feedback form button methods - End] ********************/




/************************  [ Utility methods - Start] ********************/

/*regexFindPatternAndApplyStyle("78 k", "78 kinross street,Blockhouse Bay","<b>$1</b>")*/
function regexFindPatternAndApplyStyle(pattern, text, patternReplace) {
    var regex = RegExp("(" + pattern.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, "\\$&") + ")", "gi");
    return text.replace(regex, patternReplace);
};

/************************  [ Utility methods - End] ********************/

/************************  [ Plans Page Code  - Start ] ********************/



function simulateJoinPlan() {
    var currentItem;
    $('.energy-usage .step-one').each(function () {
        $(this).click(function (e) {
            $('.energy-usage .col-three ').hide();
            $(".FPD-wrapper").hide();
            $('.energy-usage .col-two ').hide();
            $('.energy-usage .col-two span.usage').hide();
            if ($(this).hasClass('selected')) {
                $('.energy-usage .col-two span.usage').each(function (i, l) {
                    $(this).addClass("simple-gray-gradient-with-border-lighter");
                    $(this).removeClass("simple-blue-gradient-with-border selected");
                    $(this).find(".button").animate({ right: "0px" }, 0);

                });
            }

            $('.energy-usage .col-two').fadeIn('slow');
            $('#initial_text').attr("style", "display:none !important;");
            $('#initial_text').removeClass("v-outer");
            $('.' + $(this).attr("id")).each(function (i, l) {
                $(this).show();
            });
        });
    });

    $('.energy-usage .step-two').each(function () {
        $(this).click(function (e) {
                $('.energy-usage .col-three ').hide();
                $('.energy-usage .col-three ').fadeIn('slow');
                setTheTextBoxValues($(this));
                $(".FPD-wrapper").hide();
                $(".FPD").html($(this).next('.FinePrint').html());
                $(".FPD-wrapper").show("slow");
                $(".FPD").removeAttr("style");


        });

    });

    $('.energy-usage .step-two a').click(
        function () {
            if ($(this).hasClass('light-box-content-no-style')) {
                return true;
            }
            else {
                window.location = $(this).attr('href');
            }
            
        }
    );


}

function setTheTextBoxValues(elem) {
    $(textBoxEBC).val($(elem).find(".pricing-footer .EBC").text());
    $(textBoxGBC).val($(elem).find(".pricing-footer .GBC").text());
    $(textBoxSO).val($(elem).find(".pricing-footer .SO").text());
}

/************************  [ Plans Page Code  - End ] ********************/

/************************  [ Page testing code ] ********************/

function initNavTest() {
    $('.left-nav li a').each(function () {
        $(this).click(function (e) {
            $('.left-nav li').removeClass('selected');
            $(this).closest('li').addClass('selected');
            e.preventDefault();
        });
    });
}


function showHideHero() {
    var show = false;

    $('.toggleBG').click(function () {
        show = !show;
        if (show) {
            $('body').addClass("with-hero");
            $('body').removeClass("without-hero");
        } else {
            $('body').removeClass("with-hero");
            $('body').addClass("without-hero");
        }
    });

    show = true;
    $('.showHide').click(function () {
        show = !show;
        if (show) {
            $('#main-hero').show();
        } else {
            $('#main-hero').hide();
        }
    });
}


function initPromo() {
    var screens = $(".promocontainer li");
    
    $(screens).each(function (i, l){

        var imageLink = $(this).find(".img-container .pillarImg");
        var img = $(this).find(".img-container img");
        
        $(this).hover(
			function (){
				$(img).attr("src", $(imageLink[1]).attr("href"));
			},
			function (){
			  	$(img).attr("src", $(imageLink[0]).attr("href"));
			}
		);

    });
}

