supplystate = null; // state
pn = null; // pn is Product ID

$(document).ready(function() {

    // Set page colour
    // supplystate = $("#C_Supply_State").val();
    // pn = $("#Qu_Product").val();
    // if (pn == 1 || pn == 9) { $("body, #page").addClass("orange"); }
    // if (pn == 2 || pn == 5 || pn == 4 || pn == 7 || pn == 10) { $("body, #page").addClass("green"); }
    // if (pn == 8) { $("body, #page").addClass("blue"); }
    // if (pn == 3 ||  pn == 6 || pn == 11 || pn == 12) { $("body, #page").addClass("red"); }

    // Menu
    // Highlights active option depending on product id
    var currentproduct = $("#Qu_Product").val();
    function returntoactive() {
        // if (currentproduct == 1) { $("ul#menu").css({ 'background-position': '0 -40px' }); } 	// Res Black
        //         if (currentproduct == 2) { $("ul#menu").css({ 'background-position': '0 -80px' }); } 	// Res Green
        //         if (currentproduct == 3) { $("ul#menu").css({ 'background-position': '0 -320px' }); } 	// Port Power
        //         if (currentproduct == 4) { $("ul#menu").css({ 'background-position': '-83px -280px' }); } 	// Mates Black
        //         if (currentproduct == 5) { $("ul#menu").css({ 'background-position': '-83px -280px' }); } 	// Mates Green
        //         if (currentproduct == 6) { $("ul#menu").css({ 'background-position': '0 -160px' }); } 	// Staff Black
        //         if (currentproduct == 7) { $("ul#menu").css({ 'background-position': '0 -200px' }); } 	// Staff Green
        //         if (currentproduct == 8) { $("ul#menu").css({ 'background-position': '0 -120px' }); } 	// Green Premium
        //         if (currentproduct == 9) { $("ul#menu").css({ 'background-position': '0 0' }); } 		// SME Black
        //         if (currentproduct == 10) { $("ul#menu").css({ 'background-position': '0 0' }); } 		// SME Green
    }

    returntoactive(); 				// initiate the active link

    $("ul#menu li").hover(function() {	// rollover
        // if ($(this).attr("id") == "menuitem-1") { $("ul#menu").css({ 'background-position': '0 -40px' }); } 	// Res Black
        // if ($(this).attr("id") == "menuitem-2") { $("ul#menu").css({ 'background-position': '0 -80px' }); } 	// Res Green
        // if ($(this).attr("id") == "menuitem-3") { $("ul#menu").css({ 'background-position': '0 -320px' }); } 	// Port Power
        // if ($(this).attr("id") == "menuitem-4") { $("ul#menu").css({ 'background-position': '-83px -280px' }); } 	// Mates Black
        // if ($(this).attr("id") == "menuitem-5") { $("ul#menu").css({ 'background-position': '-83px -280px' }); } 	// Mates Green
        // if ($(this).attr("id") == "menuitem-6") { $("ul#menu").css({ 'background-position': '0 -160px' }); } 	// Staff Black
        // if ($(this).attr("id") == "menuitem-7") { $("ul#menu").css({ 'background-position': '0 -200px' }); } 	// Staff Green
        // if ($(this).attr("id") == "menuitem-8") { $("ul#menu").css({ 'background-position': '0 -120px' }); } 	// Green Premium
        // if ($(this).attr("id") == "menuitem-9") { $("ul#menu").css({ 'background-position': '0 0' }); } 		// SME Black
        // if ($(this).attr("id") == "menuitem-10") { $("ul#menu").css({ 'background-position': '0 0' }); } 		// SME Green
    }, function() {						// rollout
        returntoactive();
    });


    // Reactivate sIFR with time limit
    function reactivateSIFRwithtime() {
        setTimeout(function() {	// waits for the new window to open
            //reactivateSIFR(); // calls the function in sifr-config.js to reactive all sifr elements
        }, 1000);
    }

    // Adds arrow for tip and message boxes on signup page
    $("div.hasarrow").each(function() {
        var getMessages = $(this).html();
        $(this).html(getMessages + '<span class="arrow"></span>');
    });

    //initialise badnessreduction (may come using browser back button with a different amount)
    //works just for landing pages - black and hawks
	$("#badnessreduction").val("220.00");
    //works just for landing pages - mates black (vic)
	if (pn == 4) {$("#badnessreduction").val("240.00");}

    // Shows the Request a Call Back panel
    $("#requestcallbackbutton").click(function() {
        /*HideBoxMessages();
        fadefieldsets(false);
        $("#rcbDiv").fadeIn(700, function() {
            // setTimeout(function() { reactivateSIFR(); }, 100);
        } // reactive sIFR
	    );*/
        InitRcbForm();
        return false;
    });

    // Toggles any area with a class of toggle on the activation element and a div with class togglearea within its container
    // For example : Sign up process - Add Secondary Contact and Mailing Address
    $("input.toggle:checked, a.expand").each(function() {				// depending on class or chaecked status
        $(this).parent().parent().children("div.togglearea").hide(); // hides the toggable area
    });
    $(".toggle").click(function() {										// toggles the toggable area
        $(this).parent().parent().children("div.togglearea").slideToggle(300);
        if ($(this).hasClass("collapse") == true) { $(this).removeClass("collapse").addClass("expand"); } else { $(this).removeClass("expand").addClass("collapse"); }
        if ($(this).hasClass("chkbox") == true) { return true; } else { return false; }
    });

    // Hides the payment details if 'Bill' option is selected in Payment Details area
    $("input[name=paymenttype]:radio").click(function() {
        var f = 300;
        if ($('#bill').is(':checked')) {
            $("#autoPayment, #paymenttip").fadeOut(f);
        } else {
            $("#autoPayment, #paymenttip").fadeIn(f);
        }
    });

    // Money ticker on product selection page

    if ((pn == 1 && supplystate == "VIC") || pn == 11 || pn == 4) {
        $("body").find("#stepthrougharea").each(function() { 	
			updateMonies();
		});
    }

    // Product selection boxes
    $("span.fakecheckbox").click(function() {
        var c = $(this).parent().attr("class");
        if (c == "checked") {
            SwitchOptionOff(this);
        } else {
            SwitchOptionOn(this);
        }
    });

    // Open links in a new window if rel is set to external
    $('a[rel="external"]').click(function() { window.open($(this).attr('href')); return false; });

    StoreGasSelection(null);    //put current gas tick box value to an input

    // Opens a thickbox window in a thickbox window
    // To use - <a href="#" class="opentb" rel="inlinecontentid,width_of_window,height_of_window,modal(true/false)">Link name</a>
    $("a.opentb").click(function() {
        tb_remove(); 							// removes the current window
        var v = $(this).attr("rel").split(','); 	// gets the variables from the rel
        var url = SiteRoot() + "#TB_inline?height=" + v[2] + "&width=" + v[1] + "&inlineId=" + v[0] + "&modal=" + v[3] + ""; 	// sets the new url
        setTimeout(function() {						// waits for the current window to close
            tb_show("", url); 					// opens the new window
        }, 500);
        return false; 							// stops the addition of # to the url
    });

    // Initialise the date pickers and disable certain dates / days if required
    var vicPublicHoliday = {};
    // source: http://www.vic.gov.au/Victorian-Public-Holiday-Dates.html
    //2009 holidays
    vicPublicHoliday['d' + ((new Date(2009, 0, 1)).getTime())] = 'New Year\'s day';
    vicPublicHoliday['d' + ((new Date(2009, 0, 26)).getTime())] = 'Australia Day';
    vicPublicHoliday['d' + ((new Date(2009, 2, 9)).getTime())] = 'Labour Day';
    vicPublicHoliday['d' + ((new Date(2009, 3, 10)).getTime())] = 'Good Friday';
    vicPublicHoliday['d' + ((new Date(2009, 3, 11)).getTime())] = 'The Saturday before Easter Sunday';
    vicPublicHoliday['d' + ((new Date(2009, 3, 13)).getTime())] = 'Easter Monday';
    vicPublicHoliday['d' + ((new Date(2009, 3, 25)).getTime())] = 'ANZAC Day';
    vicPublicHoliday['d' + ((new Date(2009, 5, 8)).getTime())] = 'Queen\'s Birthday';
    vicPublicHoliday['d' + ((new Date(2009, 10, 3)).getTime())] = 'Melbourne Cup Day';
    vicPublicHoliday['d' + ((new Date(2009, 11, 25)).getTime())] = 'Christmas Day';
    vicPublicHoliday['d' + ((new Date(2009, 11, 26)).getTime())] = 'Boxing Day';
    vicPublicHoliday['d' + ((new Date(2009, 11, 28)).getTime())] = 'Boxing Day Additional Day';
    //2010 holidays
    vicPublicHoliday['d' + ((new Date(2010, 0, 1)).getTime())] = 'New Year\'s day';
    vicPublicHoliday['d' + ((new Date(2010, 0, 26)).getTime())] = 'Australia Day';
    vicPublicHoliday['d' + ((new Date(2010, 2, 8)).getTime())] = 'Labour Day';
    vicPublicHoliday['d' + ((new Date(2010, 3, 2)).getTime())] = 'Good Friday';
    vicPublicHoliday['d' + ((new Date(2010, 3, 3)).getTime())] = 'The Saturday before Easter Sunday';
    vicPublicHoliday['d' + ((new Date(2010, 3, 5)).getTime())] = 'Easter Monday';
    vicPublicHoliday['d' + ((new Date(2010, 3, 26)).getTime())] = 'ANZAC Day';
    vicPublicHoliday['d' + ((new Date(2010, 5, 14)).getTime())] = 'Queen\'s Birthday';
    vicPublicHoliday['d' + ((new Date(2010, 10, 2)).getTime())] = 'Melbourne Cup Day';
    vicPublicHoliday['d' + ((new Date(2010, 11, 25)).getTime())] = 'Christmas Day ';
    vicPublicHoliday['d' + ((new Date(2010, 11, 27)).getTime())] = 'Christmas Day Substitute';
    vicPublicHoliday['d' + ((new Date(2010, 11, 26)).getTime())] = 'Boxing Day';
    vicPublicHoliday['d' + ((new Date(2010, 11, 28)).getTime())] = 'Boxing Day Additional Day';

    var saPublicHoliday = {};
    // source: http://www.safework.sa.gov.au/show_page.jsp?id=2483
    //2009 holidays
    saPublicHoliday['d' + ((new Date(2009, 0, 1)).getTime())] = 'New Year\'s day';
    saPublicHoliday['d' + ((new Date(2009, 0, 26)).getTime())] = 'Australia Day';
    saPublicHoliday['d' + ((new Date(2009, 2, 9)).getTime())] = 'Adelaide Cup';
    saPublicHoliday['d' + ((new Date(2009, 3, 10)).getTime())] = 'Good Friday';
    saPublicHoliday['d' + ((new Date(2009, 3, 11)).getTime())] = 'The Saturday before Easter Sunday';
    saPublicHoliday['d' + ((new Date(2009, 3, 13)).getTime())] = 'Easter Monday';
    saPublicHoliday['d' + ((new Date(2009, 3, 25)).getTime())] = 'ANZAC Day';
    saPublicHoliday['d' + ((new Date(2009, 5, 8)).getTime())] = 'Queen\'s Birthday / Volunteer\'s Day';
    saPublicHoliday['d' + ((new Date(2009, 9, 5)).getTime())] = 'Labour Day';
    saPublicHoliday['d' + ((new Date(2009, 11, 25)).getTime())] = 'Christmas Day';
    saPublicHoliday['d' + ((new Date(2009, 11, 28)).getTime())] = 'Proclamation Day';
    //2010 holidays
    saPublicHoliday['d' + ((new Date(2010, 0, 1)).getTime())] = 'New Year\'s day';
    saPublicHoliday['d' + ((new Date(2010, 0, 26)).getTime())] = 'Australia Day';
    saPublicHoliday['d' + ((new Date(2010, 2, 8)).getTime())] = 'Adelaide Cup';
    saPublicHoliday['d' + ((new Date(2010, 3, 2)).getTime())] = 'Good Friday';
    saPublicHoliday['d' + ((new Date(2010, 3, 3)).getTime())] = 'The Saturday before Easter Sunday';
    saPublicHoliday['d' + ((new Date(2010, 3, 5)).getTime())] = 'Easter Monday';
    saPublicHoliday['d' + ((new Date(2010, 3, 26)).getTime())] = 'ANZAC Day';
    saPublicHoliday['d' + ((new Date(2010, 5, 14)).getTime())] = 'Queen\'s Birthday / Volunteer\'s Day';
    saPublicHoliday['d' + ((new Date(2010, 9, 4)).getTime())] = 'Labour Day';
    saPublicHoliday['d' + ((new Date(2010, 11, 25)).getTime())] = 'Christmas Day';
    saPublicHoliday['d' + ((new Date(2010, 11, 27)).getTime())] = 'Christmas Day Substitute';
    saPublicHoliday['d' + ((new Date(2010, 11, 28)).getTime())] = 'Proclamation Day';

    var markVicPublicHolidays = function($td, thisDate, month, year) {
        if (vicPublicHoliday['d' + thisDate.getTime()]) {
            $td.addClass('public-holiday disabled').html(thisDate.getDate()); // disable public holidays
            $td.prev().addClass('disabled');
        }
        if (thisDate.getDay() == 5) {
            $td.addClass('friday disabled').html(thisDate.getDate()); // disable Fridays
        }
        if (thisDate.getDay() == 6 || thisDate.getDay() == 0) {
            $td.addClass('weekends disabled').html(thisDate.getDate()); // disable weekends
        }
    }
    var markSAPublicHolidays = function($td, thisDate, month, year) {
        if (vicPublicHoliday['d' + thisDate.getTime()]) {
            $td.addClass('public-holiday disabled').html(thisDate.getDate()); // disable public holidays
            $td.prev().addClass('disabled');
        }
        if (thisDate.getDay() == 5) {
            $td.addClass('friday disabled').html(thisDate.getDate()); // disable Fridays
        }
        if (thisDate.getDay() == 6 || thisDate.getDay() == 0) {
            $td.addClass('weekends disabled').html(thisDate.getDate()); // disable weekends
        }
    }

    $('input.date-picker-birthday').datePicker({ createButton: false, startDate: '01/01/1901', endDate: GetMinDobDate().asString('dd/mm/yyyy') }).dpSetOffset(22, 0).bind(
				'focus',
				function(event, message) {
				    if (message == $.dpConst.DP_INTERNAL_FOCUS) {
				        return true;
				    }
				    var dp = this;
				    var $dp = $(this);
				    $dp.dpDisplay();
				    $('*').bind(
						'focus.datePicker',
						function(event) {
						    var $focused = $(this);
						    if (!$focused.is('.dp-applied')) // don't close the focused date picker if we just opened a new one!
						    {
						        // if the newly focused element isn't inside the date picker and isn't the original element which triggered
						        // the opening of the date picker

						        if ($focused.parents('#dp-popup').length == 0 && this != dp && !($.browser.msie && this == document.body)) {
						            $('*').unbind('focus.datePicker');
						            $dp.dpClose();
						        }
						    }
						}
					);
				    return false;
				}
			).bind(
				'dpClosed',
				function(event, selected) {
				    $('*').unbind('focus.datePicker');
				}
			);
    var d = $('#minReadingDate').val();
    if (supplystate == "SA") {
        var s = markSAPublicHolidays;
    } else {
        var s = markVicPublicHolidays;
    }
    $('input.date-picker-meterreading').datePicker({ createButton: false, renderCallback: s }).dpSetStartDate(d).dpSetOffset(35, 7).bind(
				'focus',
				function(event, message) {
				    if (message == $.dpConst.DP_INTERNAL_FOCUS) {
				        return true;
				    }
				    var dp = this;
				    var $dp = $(this);
				    $dp.dpDisplay();
				    $('*').bind(
						'focus.datePicker',
						function(event) {
						    var $focused = $(this);
						    if (!$focused.is('.dp-applied')) // don't close the focused date picker if we just opened a new one!
						    {
						        // if the newly focused element isn't inside the date picker and isn't the original element which triggered
						        // the opening of the date picker

						        if ($focused.parents('#dp-popup').length == 0 && this != dp && !($.browser.msie && this == document.body)) {
						            $('*').unbind('focus.datePicker');
						            $dp.dpClose();
						        }
						    }
						}
					);
				    return false;
				}
			).bind(
				'dpClosed',
				function(event, selected) {
				    $('*').unbind('focus.datePicker');
				}
			);

});

// Toggles the fieldsets on the signup page
function fadefieldsets(on) {
    // if (!on) {
    //         $("div.formcontainer").find("div.left, div.right, div.makedisable").
    //             fadeTo(300, 1).find("input, select").removeAttr("disabled");
    //     } else {
    //     $("div.formcontainer").find("div.left, div.right, div.makedisable").
    //             fadeTo(300, 0.5).find("input, select").attr("disabled", "disabled");
    //     }
}

function GetMinDobDate() {
    var today = new Date();
    var minDate = new Date();
    minDate.setFullYear(today.getFullYear() - 18);
    return minDate;
}

function SwitchOptionOn(span) {
    $(span).parent().removeClass("unchecked").addClass("checked");
    if ((pn == 1 && supplystate == "VIC") || pn == 11 || pn == 4) {
        var updatedamount = $(span).attr("rel");
        $("#badnessreduction").val(Number(parseFloat($("#badnessreduction").val()) + parseFloat(updatedamount)).toFixed(2));
        updateMonies();
    }
    StoreGasSelection(span);
}

function SwitchOptionOff(span) {
    $(span).parent().removeClass("checked").addClass("unchecked");
    if ((pn == 1 && supplystate == "VIC") || pn == 11 || pn == 4) {
        var updatedamount = $(span).attr("rel");
        $("#badnessreduction").val(Number(parseFloat($("#badnessreduction").val()) - parseFloat(updatedamount)).toFixed(2));
        updateMonies();
    }
    StoreGasSelection(span);
}

// Store gas selection
function StoreGasSelection(elem) {
    if (elem == null) {
        elem = $("#gascheckbox");
        //restore it with initial loading
        if ($("#QET_ID").length && $("#QET_ID").val().length) {
            $(elem).parent().attr("class", $("#QET_ID").val() == "DUAL" ? "checked" : "unchecked");
        }
        if ($("#QET_ID").val() == "ELEC") {
            SwitchOptionOff(elem);
        }
    }
    if ($(elem).attr("id") == "gascheckbox") {
        var c = $(elem).parent().attr("class");
        var isSelected = c == "checked";
        $("#QET_ID").val(isSelected ? "DUAL" : "ELEC");
    }
}

function updateMonies() {
    if ($("#badnessreduction").length)
    {
        var aa = $("#badnessreduction").val().split('');
        var html = '<span class="dollar">$</span>'; 				// initialise html
        for (var i = 0; i < aa.length; i++) {
            var a = aa[i];
            if (a == ".") { var a = "d"; }
            if (a == "-") { var a = "e"; }
            html += '<span class="n' + a + '">' + a + '</span>';
        }
        $("#amount").replaceWith('<div id="amount">' + html + '</div>');
    }
}
