﻿function getCalendar(m,y) {

    jQuery.ajax({
        url: "OasisService.asmx/GetCalendar",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{\"month\": \"" + m + "\",\"year\": \"" + y + "\"}",
        cache: false,
        success: function(data) {
            showCalendar(data.d);
        },
        error: function(xhr) {
            //alert('Error!  Status = ' + xhr.status);
        }
    });
}

function showCalendar(d) {
    if (!d) return;

    s = "<table><tr><td class='calendar_header'>S</td><td class='calendar_header'>M</td><td class='calendar_header'>T</td><td class='calendar_header'>W</td><td class='calendar_header'>T</td><td class='calendar_header'>F</td><td>S</td></tr><tr>";
    if (d.Start < 7) {
        for (var i = 0; i < d.Start; i++) {
            s += "<td></td>";
        }
    }
    for (var i = 0; i < d.Days.length; i++) {
        s += "<td class='calendar_td " + d.Days[i].type + "'>" + d.Days[i].day + "</td>";
        if ((d.Start + d.Days[i].day) % 7 == 0) {
            s += "</tr><tr>";
        }
    }
    s += "</tr></table>";


    jQuery("#current_month_year").val(d.currentMonth + "," + d.currentYear);
    
    jQuery("#calendar").html(s);
    jQuery("#currmonth").text(d.Name);

    jQuery("#prevmonth").data("ref", d.PrevLink);
    jQuery("#nextmonth").data("ref", d.NextLink);

    jQuery(".calendar_td").click(function() {
        var idx = parseInt(this.innerHTML) - 1;
        bindAppointment(d.Days[idx].appointment);
        bindTreatment(d.Days[idx].treatment);
        jQuery("#appointment_day_input").val(d.Days[idx].name);
        jQuery("#treatment_day_input").val(d.Days[idx].name);
        jQuery("#appointment_day").text(d.Days[idx].displayname);
        jQuery("#treatment_day").text(d.Days[idx].displayname);
        if (jQuery(this).is(".appointment")) {
            showAppointment();
        }
        else if (jQuery(this).is(".treatment")) {
            showTreatment();
        }
        else showAppointment();
    });
}

function getCal(a) {
    var params = jQuery(a).data("ref").split(",");
    getCalendar(params[0], params[1]);
    return false;
}


function hideTreatment() {
    jQuery("#treatment_container").animate({ left: 500 }, 500, function() {
        jQuery(this).hide();
    });
    hideBadgePopup();
}

function hideAppointment() {
    jQuery("#appointment_container").animate({ left: 500 }, 500, function() {
        jQuery(this).hide();
    });
    hideBadgePopup();
}

function showAppointment() {
    var targetOffset = jQuery("#main").offset().top + 116;
    jQuery('html,body').animate({ scrollTop: targetOffset }, 600);
    hideTreatment();
    jQuery("#appointment_container").prependTo("#main").show().animate({ left: -43 }, 1200);
    jQuery("#appointment_saved").hide();
    jQuery("#treatment_saved").hide();
    hideBadgePopup();
    if ((jQuery("#appointmentid").val() != null) && ((jQuery("#appointmentid").val() != "0"))) {
        jQuery("#btnDeleteAppointment").show();
    }
    else {
        jQuery("#btnDeleteAppointment").hide();
    }
}

function bindAppointment(d) {
    if (d) {
        jQuery("#appointmentid").val(d.id);
        jQuery("#appointment_container :text").each(function() {
            this.value = d[this.name] == null ? "" : d[this.name];
        });
        jQuery("#appointment_container select").each(function() {
        
            var propName = this.name;
            if (propName.indexOf("ddlAppKind") != -1) {
                propName = "kind";
                jQuery(this).val(d[propName] == null ? "" : "{" + d[propName].toUpperCase() + "}");
            } else
                if (propName.indexOf("ddlCountry") != -1) {
                    propName = "country";
                jQuery(this).val(d[propName] == null ? "" : "{" + d[propName].toUpperCase() + "}");

            } else
                if (propName.indexOf("ddlProvinces") != -1) {
                    propName = "province";
                jQuery(this).val(d[propName] == null ? "" : "{" + d[propName].toUpperCase() + "}");

            } else {
                jQuery(this).val(d[propName] == null ? "" : d[propName]);
            }
        });
        jQuery("[name='remindme']").attr("checked", d.remindme == "true");
    }
}

function showTreatment() {
    var targetOffset = jQuery("#main").offset().top + 116;
    jQuery('html,body').animate({ scrollTop: targetOffset }, 600);
    hideAppointment();
    jQuery("#treatment_container").prependTo("#main").show().animate({ left: -43 }, 1200);
    jQuery("#appointment_saved").hide();
    jQuery("#treatment_saved").hide();
    hideBadgePopup();
}

function bindTreatment(d) {
    if (d) {
    
        jQuery("#treatmentid").val(d.id);
        jQuery("#treatment_container select").each(function() {

            var propName = this.name;
            if (propName.indexOf("ddlWho") != -1) {
                propName = "who";
                jQuery(this).val(d[propName] == null ? "" : "{" + d[propName].toUpperCase() + "}");
            } else
                if (propName.indexOf("ddlWhere") != -1) {
                propName = "where";
                jQuery(this).val(d[propName] == null ? "" : "{" + d[propName].toUpperCase() + "}");

            } else
                if (propName.indexOf("ddlRate") != -1) {
                propName = "rate";
                jQuery(this).val(d[propName] == null ? "" : "{" + d[propName].toUpperCase() + "}");

            } else {
                jQuery(this).val(d[propName] == null ? "" : d[propName]);
            }


        });
        jQuery("[name='take_today']:eq(0)").attr("checked", d.take_today == "yes");
        jQuery("[name='take_today']:eq(1)").attr("checked", d.take_today == "no");
    }
}

function saveAppointment() {
    var d = "{\"appointment\":{";
    d += "\"id\":\"" + jQuery("#appointmentid").val() + "\",";
    d += "\"name\":\"" + jQuery("#appointment_day_input").val().replace(',', ' ') + "\",";
    d += "\"remindme\":\"" + jQuery("[name='remindme']").is(':checked') + "\",";

    jQuery("#appointment_container :text").each(function() {
        d += "\"" + this.name + "\":\"" + this.value + "\","
    });
    jQuery("#appointment_container select").each(function() {
        var propName = this.name;
        var propValue = this.value;

        if (propName.indexOf("ddlAppKind") != -1) {
            propName = "kind";
            propValue = this.value;
        }

        if (propName.indexOf("ddlCountry") != -1) {
            propName = "country";
            propValue = this.value;
        }

        if (propName.indexOf("ddlProvinces") != -1) {
            propName = "province";
            propValue = this.value;
        }

        d += "\"" + propName + "\":\"" + propValue + "\","

    });
    d = d.substr(0, d.length - 1);
    d += "}}";
    jQuery.ajax({
        url: "OasisService.asmx/SaveAppointment",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: d,
        cache: false,
        success: function(data) {
        jQuery("#appointment_saved").css("left", jQuery("#custombutton").offset().left - 125);
        jQuery("#appointment_saved").css("top", jQuery("#custombutton").offset().top - 293);
            jQuery("#appointment_saved").show();
            showBadgePopup(jQuery("#appointment_saved").offset().top + 90);
            var params = jQuery("#current_month_year").val().split(",");
            getCalendar(params[0], params[1]);

        },
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status);
        }
    });
}

function deleteAppointment() {
    var answer = confirm("Delete?")
    if (answer) {
        var d = "{\"appointment\":{";
        d += "\"id\":\"" + jQuery("#appointmentid").val() + "\",";
        d += "\"name\":\"" + jQuery("#appointment_day_input").val().replace(',', ' ') + "\",";
        d += "\"remindme\":\"" + jQuery("[name='remindme']").is(':checked') + "\",";

        jQuery("#appointment_container :text").each(function() {
            d += "\"" + this.name + "\":\"" + this.value + "\","
        });
        jQuery("#appointment_container select").each(function() {
            var propName = this.name;
            var propValue = this.value;

            if (propName.indexOf("ddlAppKind") != -1) {
                propName = "kind";
                propValue = this.value;
            }

            if (propName.indexOf("ddlCountry") != -1) {
                propName = "country";
                propValue = this.value;
            }

            if (propName.indexOf("ddlProvinces") != -1) {
                propName = "province";
                propValue = this.value;
            }

            d += "\"" + propName + "\":\"" + propValue + "\","

        });
        d = d.substr(0, d.length - 1);
        d += "}}";
        if ((jQuery("#appointmentid").val() != null) && (jQuery("#appointmentid").val() != "")) {
            jQuery.ajax({
                url: "OasisService.asmx/DeleteAppointment",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: d,
                cache: false,
                success: function(data) {
                    hideAppointment();
                    var params = jQuery("#current_month_year").val().split(",");
                    getCalendar(params[0], params[1]);

                },
                error: function(xhr) {
                    alert('Error!  Status = ' + xhr.status);
                }
            });
        }
    }
}


function clearAppointmentTab() {
    jQuery("#appointment_container :text").each(function() {
        this.value = "";
    });
    jQuery("#appointment_container select").each(function() {
        this.selectedIndex = 0; 
    });
}


function saveTreatment() {
    var d = "{\"treatment\":{";
    d += "\"id\":\"" + jQuery("#treatmentid").val() + "\",";
    d += "\"name\":\"" + jQuery("#treatment_day_input").val().replace(',', ' ') + "\",";
    d += "\"take_today\":\"" + jQuery("input[name='take_today']:checked").val() + "\",";
    jQuery("#treatment_container select").each(function() {
        var propName = this.name;
        var propValue = this.selectedIndex;
        
        if (propName.indexOf("ddlWho") != -1) {
            propName = "who";
            propValue = this.value;
        }
        if (propName.indexOf("ddlWhere") != -1) {
            propName = "where";
            propValue = this.value;
        }

        if (propName.indexOf("ddlRate") != -1) {
            propName = "rate";
            propValue = this.value;
        }

        if ((propName == "when_hour") || (propName == "when_minute") || (propName == "when_ampm"))
        {
            propValue = this.value;
        }
        
        d += "\"" + propName + "\":\"" + propValue + "\","

    });
    d = d.substr(0, d.length - 1);
    d += "}}";
    jQuery.ajax({
        url: "OasisService.asmx/SaveTreatment",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: d,
        cache: false,
        success: function(response) {
        jQuery("#treatmentid").val(response.d);
        jQuery("#treatment_saved").css("left", jQuery("#custombutton").offset().left - 125);
        jQuery("#treatment_saved").css("top", jQuery("#custombutton").offset().top - 293);
            jQuery("#treatment_saved").show();
            showBadgePopup(jQuery("#treatment_saved").offset().top + 70);
            var params = jQuery("#current_month_year").val().split(",");
            getCalendar(params[0], params[1]);

        },
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status);
        }
    });
}

function getChirps() {
    jQuery.ajax({
        url: "OasisService.asmx/GetChirps",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "",
        cache: false,
        success: function(data) {
            showChirps(data.d);
        },
        error: function(xhr) {
            //alert('Error!  Status = ' + xhr.status);
        }
    });
}

function showChirps(d) {
    jQuery("#chirps_num").text(d.length);
    jQuery("#chirps").empty();
    jQuery("#chirpsTemplate").tmpl(d).appendTo("#chirps");
    var num = parseInt(jQuery("#chirps_num").text());
    if (num == 0) hideChirps();
}

function hideChirp(id) {
    jQuery("#chirp" + id + " td").fadeOut('slow', function() {
        jQuery(this).parent().remove();
    });
    var num = parseInt(jQuery("#chirps_num").text()) - 1;
    jQuery("#chirps_num").text(num);
    var num = parseInt(jQuery("#chirps_num").text());
    if (num == 0) hideChirps();
}

function hideChirps() {

    jQuery("#chirps").slideUp("slow");
    var btn = jQuery("#updown2");
    if (btn.is(".on")) btn.removeClass("on");
}

function chirpBack(id) {
    jQuery.ajax({
        url: "OasisService.asmx/ChirpBack",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{\"id\": \"" + id + "\"}",
        cache: false,
        success: function(data) {
            showBadgePopup(jQuery("#chirpBack").offset().top);
            hideChirp(id);
            
        },
        error: function(xhr) {
            //alert('Error!  Status = ' + xhr.status);
        }
    });
}

function chirpUser(userId) {
    jQuery.ajax({
        url: "OasisService.asmx/ChirpUser",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{\"userId\": \"" + userId + "\"}",
        cache: false,
        success: function(data) {

            showBadgePopup(jQuery("#feedItemDetail").offset().top);
            getChirps();
        },
        error: function(xhr) {
            //alert('Error!  Status = ' + xhr.status);
        }
    });
}

function chirpUserFlash(userId) {
    jQuery.ajax({
        url: "OasisService.asmx/ChirpUser",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{\"userId\": \"" + userId + "\"}",
        cache: false,
        success: function(data) {
            jQuery.ajax({
                url: "OasisService.asmx/GetChirpMessage",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                success: function(data) {
                    alert(data.d);
                    getChirps();
                },
                error: function(xhr) {
                }
            });
        },
        error: function(xhr) {
        }
    });
}

function ignoreChirp(id) {
    jQuery.ajax({
        url: "OasisService.asmx/IgnoreChirp",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{\"id\": \"" + id + "\"}",
        cache: false,
        success: function(data) {
            showBadgePopup(jQuery("#chirpBack").offset().top);
            hideChirp(id);
        },
        error: function(xhr) {
            //alert('Error!  Status = ' + xhr.status);
        }
    });
}

function saveBirdImage() {
    var d = "{\"birdimage\":{";
    d += "\"birdUrl\":\"" + jQuery("[id*='avatarImage']").val() + "\",";
    d += "\"birdAvatar\":\"" + jQuery("[id*='avatar']").val() + "\"";
    d += "}}";
    jQuery.ajax({
        url: "OasisService.asmx/SaveBirdImage",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: d,
        cache: false,
        success: function(data) {
            var currentAvatar = jQuery("[id*='inpUserBirdAvatarUrl']");
            var avatarToSet = jQuery("[id*='avatarImage']").val();
            currentAvatar.val(avatarToSet);

            var currentAvatarThumb = jQuery("[id*='inpBirdThumbUrl']");
            var avatarThumbToSet = jQuery("[id*='inpBirdThumbUrlSelected']").val();
            currentAvatarThumb.val(avatarThumbToSet);
            var img1 = jQuery("#profile-bird-small");
            img1.attr("src", avatarThumbToSet);

            
            alert('Saved');
            closePopin(true, null, 'editbird');
        },
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status);
        }
    });
}

function getFeedItems(i,max, newsDiv) {

    jQuery.ajax({
        url: "OasisService.asmx/GetFeedItems",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{\"i\": \"" + i + "\", \"max\": \"" + max + "\"}",
        cache: false,
        success: function(data) {
            jQuery(newsDiv).empty();
            jQuery("#feedItemTemplate").tmpl(data.d).appendTo(newsDiv);

            // bind only once !
            if ( (max > 5) || (newsDiv = "#feedItemsHome"))
            {
                jQuery(".feed_item_link").click(function(e) {
                    e.preventDefault();
                    var id = jQuery(this).closest("div").attr("id"); 

                    showFeedItem(id, jQuery(this).offset().top);
                });
            }
        },
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status);
        }
    });
}

function showFeedItem(id, top) {
    jQuery.ajax({
        url: "OasisService.asmx/GetFeedItemDetail",
        type: "POST",
        data: "{\"id\": \"" + id + "\"}",
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function(data) {
            if (data.d != null) {
                if (data.d.IsLoggedIn) {
                    jQuery("#feedItemDetail").empty();
                    jQuery("#feedTemp").tmpl(data.d).appendTo("#feedItemDetail");
                    jQuery("#feeditem_popup").show();
                    jQuery("#feeditem_popup").css({ top: top - 10 });

                    jQuery("#chirpmelink").click(function(e) {
                        e.preventDefault();
                        var id = jQuery(this).closest("div").attr("id");
                        chirpUser(id);
                        jQuery.ajax({
                            url: "OasisService.asmx/GetChirpMessage",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            cache: false,
                            success: function(data) {
                                alert(data.d);
                            },
                            error: function(xhr) {
                            }
                        });
                    });


                } else {
                    jQuery("#feedItemDetail").empty();
                    jQuery("#feedTempPublic").tmpl(data.d).appendTo("#feedItemDetail");
                    jQuery("#feeditem_popup").show();
                    jQuery("#feeditem_popup").css({ top: top - 10 });
                }
            }
        },
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status);
        }
    });
}

function hideFeedItem() {
    jQuery("#feeditem_popup").hide();
}

function RefreshNews() {
    getFeedItems(1, 5, "#feedItems");
    getFeedItems(6, 15, "#morenews");
}

function showBadgePopup(top) {
    jQuery.ajax({
        url: "OasisService.asmx/GetBadgeAch",
        type: "POST",
        data: "{\"id\": \"" + top + "\"}",
        contentType: "application/json; charset=utf-8",
        cache: false,  
        success: function(data) {
            if (data.d != null) {
                jQuery("#badgeItemDetail").empty();
                jQuery("#badgeTemp").tmpl(data.d).appendTo("#badgeItemDetail");
                jQuery("#badge_update_popup").show();
                jQuery("#badge_update_popup").css({ top: top - 10 });
                jQuery("#badgeTitle").html(data.d.badgetitle + " ");
                var icon = jQuery("[id*='badgeIcon']");
                icon.attr("src", data.d.badgeicon);
            }
        },
        error: function(xhr) {
            alert('Error!  Status = ' + xhr.status);
        }
    });

}


function hideBadgePopup() {
    jQuery("#badge_update_popup").hide();
}
