var datepicker_style = {
    numberOfMonths: 1,
    onSelect: datePicked,
    changeMonth: true,
    changeYear: true,
    showOn: 'button',
    buttonImage: '/images/datepicker.jpg',
    buttonImageOnly: true
};

function datePicked(dateTime, inst)
{
   if ($(this).attr('name') == "date_start") {
       $('#date_end').datepicker('option', 'minDate', $.datepicker.parseDate("mm/dd/yy",dateTime));
   }
}

function loadForecast(page) {
    $.get("/rpc",{'action':'get_forecast','f':'"'+forecast+'"','page':page}, function(data) {
        $("#tabs-1").html(data);
    }, "text");
}

function display() {
    reloadCurrentTab();
    graphUpdate()
}

function reloadCurrentTab() {
    // reload current tab after data change
    selected = $('#data').tabs('option', 'selected');
    $('#data').tabs('load',selected);
}

function graphUpdate()
{
    url = "/rpc?action=get_graph&f="+forecast;
    spinning_wheel = true;
    timeout = 10;
    retry = 1;
    mode = "reset";
    document.my_chart.Update_URL( url, spinning_wheel, timeout, retry, mode );
}

$("a.delete").live("click",function(event) {
    href = $(this).attr('href');
    
    $("#confirm_dialog_delete").dialog({
        resizable:false,
        height:180,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            'Yes, Delete It!': function() {
                $.get(href,function(data){
                    if (data == "success") {
                        display();
                        $("#confirm_dialog_delete").dialog('close');
                        $("#confirm_dialog_delete").dialog("destroy");

                    } else {
                        userAlert("Error","Error deleting event");
                    }
                },"text");

            },
            Cancel: function() {
                $(this).dialog('close');
            }
        },
        autoOpen:false
    }).dialog("open").show();
    return false;
});

function userAlert(title,message){
    $("#alert_dialog").html(message);
    $("#alert_dialog").attr('title',title)
    $("#alert_dialog").dialog({
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.7
        },
        buttons: {
            'Ok': function(){
                $("#alert_dialog").dialog("destroy");
            }
        },
        autoOpen:false
    }).dialog("open").show();
}

function editEventSubmit(){
    if ($('#edit_event').valid()) {
        $.post(href,$(":input").serialize(),function(data) {
            if (data == "success") {
                $("#edit_dialog").dialog('destroy');
                display();
            } else {
                userAlert('Error','The following fields are required but are not correct: ' + data);
            }
        },"text");
    } else {
        userAlert("Error","Description, Amount and Date fields are required.")
    }
}

function init_edit() {
    $('.dates').datepicker(datepicker_style);
    //$('#edit_event').submit(editEventSubmit);
    $('#edit_event').validate({
        showErrors: function(errorMap, errorList) {},
        submitHandler: editEventSubmit
    });
    $("#event_name").focus();

}

$("a.edit").live("click",function(event) {
    href = $(this).attr('href');
    $("#edit_dialog").html("One moment please ...");
    $("#edit_dialog").load(href,"",init_edit);

    $("#edit_dialog").dialog({
        resizable:false,
        width:700,
        
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.7
        },
        buttons: {
            'Delete': function () {
                var eventId = $("#event_id").val();
                if (eventId) {
                    $("#confirm_dialog").dialog({
                        resizable:false,
                        height:180,
                        modal: true,
                        overlay: {
                            backgroundColor: '#000',
                            opacity: 0.5
                        },
                        buttons: {
                            'Yes, Delete It!': function() {
                                var forecastId = $("#forecast_id").val();
                                var eventId = $("#event_id").val();

                                $.get("/rpc",{'action':'delete_event','f':forecastId,'e':eventId},function(data){
                                    if (data == "success") {
                                        $("#confirm_dialog").dialog('close');
                                        $("#edit_dialog").dialog('close');
                                        display();
                                    } else {
                                        userAlert("Error","Error deleting event");
                                    }
                                },"text");

                            },
                            Cancel: function() {
                                $(this).dialog('close');
                            }
                        },
                        autoOpen:false
                    }).dialog("open").show();
                } else {
                    $(this).dialog('destroy');
                }
            },
            'Save': editEventSubmit,
            Cancel: function() {
                $(this).dialog('destroy');
            }
        },
        autoOpen:true,
        close: function () {
            $(this).dialog('destroy');

        }
    });
    $("#edit_dialog").dialog("open");

    $("#edit_dialog").show();
    return false;
});

function forecastList() {
    $.getJSON("/rpc","action=forecasts",function(data) {
        $("#forecast_list").html('');
        for (var i=0;i<data.length;i++) {
            $("#forecast_list").append("<a href='/forecast/"+data[i].key+ "'>" + data[i].name + "</a><br />")
        }
    });
}

$(function () {
    //$("#datepicker").daterangepicker({arrows:true});
    $("#data").tabs({
        load: function(event, ui) {
            $('a.in_tab', ui.panel).live("click", function() {
                $(ui.panel).load(this.href);
                return false;
            });
        }
    });
    $("#data").show();

    function setBalanceSubmit() {
        if ($("#balance_form").valid()) {
            $.get("/rpc",{'action':'set_balance','f':forecast,'balance':$("#balance_amount").val()},function(data){
                if (data == "success") {
                    $("#balance_dialog").dialog('close');
                    display();

                } else {
                    userAlert("Error", "Error:"+data);
                }
            },"text");
        } else {
            userAlert("Error", 'Error: Invalid balance amount.');
        }
    }

    $("#set_current_balance").click(function() {
        $("#balance_form").validate({
            showErrors: function(errorMap, errorList) {},
            submitHandler: setBalanceSubmit
        });

        $("#balance_dialog").dialog({
            resizable:false,
            height:180,
            modal: true,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                'Save': setBalanceSubmit,
                'Cancel': function() {
                    $(this).dialog('close');
                }
            },
            autoOpen:false
        }).dialog("open").show();
        return false;
    });

    function newForecastSubmit() {
        if ($("#new_forecast_form").valid()) {
            $.get("/rpc",{'action':'new_forecast','name':$("#create_forecast_name").val()},function(data){
                if (data == "subscribe") {
                    userAlert("New Forecast", "Free accounts are limited to just one forecast.  Create, copy and compare more forecasts with a premium subscription.  <a href='/subscribe'>View subscription options</a>");
                } else if (data == "error") {
                    userAlert("New Forecast", "A forecast with this name already exists.  Please try again!");
                } else {
                    document.location = "/forecast/"+data
                }
            },"text");
        } else {
            userAlert("New Forecast",'Please enter forecast name');
        }
    }

    $("#new_forecast").click(function() {
        $("#new_forecast_form").validate({
            showErrors: function(errorMap, errorList) {},
            submitHandler: newForecastSubmit
        });

        $("#new_forecast_dialog").dialog({
            resizable:false,
            height:180,
            modal: true,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                'Save': newForecastSubmit,
                'Cancel': function() {
                    $(this).dialog('close');
                }
            },
            autoOpen:false
        }).dialog("open").show();
        return false;
    });

    function renameForecastSubmit() {
        if ($("#rename_forecast_form").valid()) {
            $.get("/rpc",{'action':'rename_forecast','f':forecast,'name':$("#rename_forecast_name").val()},function(data){
                if (data != "error") {
                    $("#rename_forecast_dialog").dialog('close');
                    display();
                    forecastList();

                } else {
                    userAlert("Rename Forecast","A forecast with this name already exists.  Please try again!");
                }
            },"text");
        } else {
            userAlert("Rename Forecast",'Please enter forecast name');
        }
    }
    $("#rename_forecast").click(function() {
        $("#rename_forecast_form").validate({
            showErrors: function(errorMap, errorList) {},
            submitHandler: renameForecastSubmit
        });

        $("#rename_forecast_dialog").dialog({
            resizable:false,
            height:180,
            modal: true,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                'Save': renameForecastSubmit,
                'Cancel': function() {
                    $(this).dialog('close');
                }
            },
            autoOpen:false
        }).dialog("open").show();
        return false;
    });

    $("#delete_forecast").click(function(event) {
        href = $(this).attr('href');
        
        $("#delete_forecast_dialog").dialog({
            resizable:false,
            height:180,
            modal: true,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                'Yes, Delete It!': function() {

                    $("#alert_dialog").html("One Moment Please ...");
                    $("#alert_dialog").attr('title','Deleting Forecast ...')
                    $("#alert_dialog").dialog({
                        modal: true,
                        overlay: {
                            backgroundColor: '#000',
                            opacity: 0.7
                        },
                        autoOpen:false
                    }).dialog("open").show();
                    $("#delete_forecast_dialog").dialog('close');
                    $("#delete_forecast_dialog").dialog("destroy");

                    $.get("/rpc",{'action':'delete_forecast','f':forecast},function(data) {
                        if (data == "success") {
                            document.location = "/"
                            

                        } else {
                            userAlert("Error","Error deleting forecast");
                        }
                    },"text");

                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            },
            autoOpen:false
        }).dialog("open").show();
        event.preventDefault();
    });

    $("#share_forecast").click(function(event) {
        $("#share_dialog").dialog({
            resizable:false,
            height:220,
            width:500,
            modal: true,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                'Share Forecast': function() {
                    $("#alert_dialog").html("One Moment Please ...");
                    $("#alert_dialog").dialog({
                        modal: true,
                        overlay: {
                            backgroundColor: '#000',
                            opacity: 0.7
                        },
                        autoOpen:false
                    }).dialog("open").show();
                    $("#share_dialog").dialog('close');
                    $("#share_dialog").dialog("destroy");

                    $.get("/rpc",{'action':'share_forecast','f':forecast,'e':$("#share_email").val()},function(data) {
                        if (data == "success") {
                            userAlert("Share Forecast","Successfully shared forecast.");
                        } else {
                            userAlert("Error","Error sharing forecast.  Please check the recipient email address and try again!");
                        }
                    },"text");

                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            },
            autoOpen:false
        }).dialog("open").show();
        //event.preventDefault();
        return false;
    });

    function copyForecastSubmit() {
        if ($("#copy_forecast_form").valid()) {
            $.get("/rpc",{'action':'copy_forecast','f':forecast,'name':$("#copy_forecast_name").val()},function(data){
                if (data == "subscribe") {
                    userAlert("Copy Forecast", "Free accounts are limited to just one forecast.  Create, copy and compare more forecasts with a premium subscription.  <a href='/subscribe'>View subscription options</a>");
                } else if (data == "error") {
                    userAlert("Copy Forecast", "A forecast with this name already exists.  Please try again!");
                } else {
                    document.location = "/forecast/"+data
                }
            },"text");
        } else {
            userAlert("Copy Forecast",'Please enter forecast name');
        }
        return false;
    }

    $("#copy_forecast").click(function(event) {
        $("#copy_forecast_form").validate({
            showErrors: function(errorMap, errorList) {},
            submitHandler: copyForecastSubmit
        });

        $("#copy_forecast_dialog").dialog({
            resizable:false,
            height:180,
            modal: true,
            overlay: {
                backgroundColor: '#000',
                opacity: 0.5
            },
            buttons: {
                'Save': copyForecastSubmit,
                'Cancel': function() {
                    $(this).dialog('close');
                }
            },
            autoOpen:false
        }).dialog("open").show();
        event.preventDefault();
        return false;
    });

    $(".button").hover(
        function() {
            $(this).addClass("button-hover");
        },
        function() {
            $(this).removeClass("button-hover");
        }
    );

    $("#graph_range").bind("change",function() {
        $.get("/rpc",{'action':'set_range','f':forecast,'range':$("#graph_range").val()},function(data){
            if (data == "success") {
                graphUpdate();
                reloadCurrentTab();
            }
        });
    });
    
    $("#graph_compare").bind("change",function() {
        $.get("/rpc",{'action':'set_compare','f':forecast,'c':$("#graph_compare").val()},function(data){
            if (data == "success") {
                graphUpdate();
            }
        });
    });

    $("#choose_forecast").bind("change", function() {
        document.location = "/forecast/"+$("#choose_forecast").val()
    });
});



