﻿

var timerInterval = 50;
var globe;
var activeGlobePanel;
var globeMargin;
var globeMove = true;


$(document).ready(function () {

    globe = new Globe();

    GetNewsEvents();

    $(document).everyTime(timerInterval, "update", function () { Update() });

    /*
    $("#panelEnJij").fadeOut(0);
    ShowRandomActieVanAnderen();
    $(document).everyTime(5000, "randomActieVanAnderen", function () { ShowRandomActieVanAnderen() });
    */

    $("#panelActivatieActie").fadeOut(0);
    ShowLatestActivatieActieSubmissions();
    $(document).everyTime(5000, "latestActivatieActieSubmissions", function () { ShowLatestActivatieActieSubmissions() });

    var newsEventId = getQuerystring("newsEventId");
    if (newsEventId != "") {
        ShowNewsEventPanel(newsEventId);
    }
});


function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}


function GetNewsEvents() {

    var jsonData = JSON.stringify({ "count": 10 });

    $.ajax({
        type: "POST",
        url: "http://www.unicefenjij.nu/Webservices/Unicefenjij.asmx/GetTopNewsEvents",
        contentType: "application/json; charset=utf-8",
        data: jsonData,
        dataType: "json",
        success: GetNewsEvents_OnSuccess,
        error: OnError
    });
}

function GetNewsEvents_OnSuccess(data, textStatus, XMLHttpRequest) {
    var newsEvents = data.d;

    for (var i in newsEvents) {
        var newsEvent = newsEvents[i];

        var isTopEvent = true;
        for (var j in globe.GlobeDots) {
            var globeDot = globe.GlobeDots[j];

            if ((globeDot.MapPoint.X == newsEvent.MapPoint.X) && (globeDot.MapPoint.Y == newsEvent.MapPoint.Y)) {
                isTopEvent = false;
                globeDot.AddEvent(newsEvent);
                break;
            }
        }
        if (isTopEvent) {
            globe.AddGlobeDot(new GlobeDot(newsEvent));
        }
    }

    for (var g in globe.GlobeDots) {
        var globeDot = globe.GlobeDots[g];
        globeDot.Update();
    }

    globe.GlobeDots[0].GlobePanel.ZSort();
}

function OnError(XMLHttpRequest, textStatus, errorThrown) {
    alert("Error: " + textStatus + " " + errorThrown);
}

function Update() {
    globe.Update();

    var margin = parseInt(($(window).height() * 0.5) - 320);
    if (globeMargin != margin) {
        globeMargin = margin;
        $('#globeWrapper').css("margin-top", globeMargin);
    }
}

function ShowNewsEventPanel(newsEventId) {

    globe.Paused = true;
    globe.EventOpen = true;

    var container = $(document.createElement('div'));
    $("#newsEventPanel").append(container);
    container.load(getWebserviceURL() + "utilitypages/newseventpanel.aspx?newseventid=" + newsEventId, null, newsEvent_loadHandler);
}

function newsEvent_loadHandler() {

   SetupNewsEventPanelLayout();
   $("#newsEventPanel").fadeIn(0);
   $(".closeButton").click(function () { HideNewsEventPanel(); });
   $(activeGlobePanel).click(function () { HideNewsEventPanel(); });
   $('#mainContainer').click(function (event) {

       if ($(event.target).attr("id") == "panelsOverlay") HideNewsEventPanel();
       if ($(event.target).id == "mainContainer") HideNewsEventPanel();
       if ($(event.target).id == "globeMaskLeft") HideNewsEventPanel();
       if ($(event.target).id == "globeMaskRight") HideNewsEventPanel();
   });
   globeMove = false
}

function HideNewsEventPanel() {
    if(activeGlobePanel) activeGlobePanel.RepositionPanel();
    $("#newsEventPanel").fadeOut(100, function () {
        $("#newsEventPanel").empty();
        globe.Paused = false;
        globe.EventOpen = false;
        activeGlobePanel = null;

        $('#mainContainer').unbind("click");

    });
    globeMove = true;
}


var prevTab;

function SetupNewsEventPanelLayout() {

    $('.slideShow').click(function () {
        $('#mediaViewerContent').prepend('<img id="imgMediaViewer" src="' + $(this).attr("href") + '" />')
        $('#mediaViewerCaption').html($(this).attr("title"));
        $('#mediaViewer').fadeIn(50, function () {

            $('#mediaViewerContent').click(function () {
                $('#mediaViewer').fadeOut(50, function () {
                    $('#mediaViewerContent').empty();
                });
            });

            $('#mediaViewerCloseButton').click(function () {
                $('#mediaViewer').fadeOut(50, function () {
                    $('#mediaViewerContent').empty();
                });
            });
            
        });
        return false;
    });

    $('.slideShowVideo').click(function () {
        $('#mediaViewerContent').prepend('<iframe id="fmrMediaViewer" src="' + $(this).attr("href") + '" width="540" height="380" frameborder="0"  />')
        $('#mediaViewerCaption').html($(this).attr("title"));
        $('#mediaViewer').fadeIn(50, function () {

            $('#mediaViewer').click(function () {
                $('#mediaViewer').fadeOut(50, function () {
                    $('#mediaViewerContent').empty();
                });
            });
        });
        return false;
    });


    // Setup TAF tab
    $("#TAFThankYou").hide();

    $('#btnSendTAF').click(function () {
        SendTAF();
    });


    // Setup Reactions tab
    $("#placeReactionPane").hide();
    $('#ReactionThankYou').hide();

    $('#btnPlaceReaction').click(function () {
        $("#reactionsPane").hide();
        $("#placeReactionPane").show();
    });

    $('#btnCancelReaction').click(function () {
        $("#placeReactionPane").hide();
        $("#reactionsPane").show();
    });

    $('#btnSendReaction').click(function () {
        SendReaction();
    });


    $('.linkAskUnicef').click(function () {
        $(prevTab).hide();
        $("#placeReactionPane").hide();
        $("#tabAskUnicef").show();

        $('#tabButtonReactions').removeClass("active");
        $('#tabButtonAskUnicef').addClass("active");
    });



    $("#txtReactionAge").keypress(function (e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            $("#txtReactionAgeError").html("Alleen getallen!").show().fadeOut(1000);
            return false;
        }
    });

    // Setup Question tab
    $('#AskThankYou').hide();

    $('#btnSendAsk').click(function () {
        SendQuestion();
    });

    $("#txtAskAge").keypress(function (e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            $("#txtAskAgeError").html("Alleen getallen!").show().fadeOut(1000);
            return false;
        }
    });


    $('.reactionCountLink').click(function () {

        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $('#tabButtonReactions').addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        SetMenuPosition("#tabReactions");
        $("#tabReactions").fadeIn(0);
        prevTab = $("#tabReactions");
        $('.scrollPanel').tinyscrollbar({ sizethumb: 25 });
    });

    $('#linkReaction').click(function () {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $('#tabButtonReactions').addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        SetMenuPosition("#tabReactions");
        $("#reactionsPane").hide();
        $("#placeReactionPane").show();
        $("#tabReactions").fadeIn(0);
        prevTab = $("#tabReactions");
        $('.scrollPanel').tinyscrollbar({ sizethumb: 25 });
    });

    $('#txtReactionContent').focusin(function () {
        if ($('#txtReactionContent').html() == "Vul hier je reactie in") $('#txtReactionContent').html("");
    });

    $('#txtReactionContent').focusout(function () {
        if ($('#txtReactionContent').html() == "") $('#txtReactionContent').html("Vul hier je reactie in");
    });

    $('#txtReactionContent').keyup(function () {
        var charLength = $(this).val().length;
        $('#charCountReaction').html("Nog " + (140 - charLength) + " letters");
    });

    $('.notOkayButton').click(function () {
        SendNotOkay($(this).attr("rel"));
    });

    $('.likeButton').click(function () {
        SendLike($(this).attr("rel"));
    });

    $('.dislikeButton').click(function () {
        SendDislike($(this).attr("rel"));
    });


    // Setup Tabs
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(0); //Activate first tab


    $(".tab_content:first").fadeIn(
        function () {

            $('#slidePanel').tinycarousel();
            $('#scrollPanelNewsEvent').tinyscrollbar({ sizethumb: 25 });
         });   //Show first tab content

         $("ul.tabs li").click(function () {

             $("ul.tabs li").removeClass("active"); //Remove any "active" class
             $(this).addClass("active"); //Add "active" class to selected tab
             $(".tab_content").hide(); //Hide all tab content

             if (prevTab == "#tabTAF") {
                 $("#TAFThankYou").hide();
                 $("#TAFForm").show();
             }
             if (prevTab == "#tabReactions") {
                 $("#placeReactionPane").hide();
                 $("#reactionsPane").show();
                 $("#ReactionsThankYou").hide();
                 $("#ReactionsForm").hide();
                 $("#ReactionFormError").hide();
                 $('#ReactionThankYou').hide();
             }
             if (prevTab == "#tabAskUnicef") {
                 $("#AskThankYou").hide();
                 $("#AskForm").show();
             }


             var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
             $(activeTab).fadeIn(); //Fade in the active ID content

             SetMenuPosition(activeTab);

             prevTab = activeTab;

             $('.scrollPanel').tinyscrollbar({ sizethumb: 25 });

             return false;
         });
}

function validateEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
}


function SetMenuPosition(activeTab)
{
    if (activeTab != "#tabContent") $('#newsEventPanelMenu').css('top', 20);
    else $('#newsEventPanelMenu').css('top', 210);
}

function SendTAF() {

    if (!validateEmail($('#txtTAFRecipientMailAddress').val()) ||
        $('#txtTAFSenderName').val() == "" || 
        $('#txtTAFRecipientName').val() == "" || 
        $('#txtTAFRecipientMailAddress').val() == ""){
        $('#TAFFormError').fadeIn();
        return false;
        }

    $('#TAFFormError').fadeOut();

    var tafMessage = new Object();

    tafMessage.NewsEventNodeId = activeGlobePanel.NewsEventId;
    tafMessage.SenderName = $('#txtTAFSenderName').val();
    tafMessage.RecipientName = $('#txtTAFRecipientName').val();
    tafMessage.RecipientMailAddress = $('#txtTAFRecipientMailAddress').val();

    var jsonData = JSON.stringify({ "tafMessage": tafMessage });

    $.ajax({
        type: "POST",
        url: "http://www.unicefenjij.nu/Webservices/Unicefenjij.asmx/SendTAF",
        contentType: "application/json; charset=utf-8",
        data: jsonData,
        dataType: "json",
        success: SendTAF_OnSuccess,
        error: OnError
    });

}

function SendTAF_OnSuccess(data, textStatus, XMLHttpRequest) {

    $("#TAFForm").hide();
    $("#TAFThankYou").show();
}


function SendReaction() {

    if ($('#txtReactionContent').val() == "" ||
        $('#txtReactionName').val() == "" ||
        $('#txtReactionAge').val() == "" || 
        $('#chkReactionAgree').is(':checked') == false) {
        $('#ReactionFormError').fadeIn();
        return false;
    }

    $('#ReactionFormError').fadeOut();

    var reaction = new Object();

    reaction.NewsEventNodeId = activeGlobePanel.NewsEventId;
    reaction.NameVisitor = $('#txtReactionName').val();
    reaction.Content = $('#txtReactionContent').val();
    reaction.Age = $('#txtReactionAge').val();
    reaction.IPAddress = "123";
    reaction.Banned = false;
    reaction.Likes = 0;
    reaction.Dislikes = 0;

    var jsonData = JSON.stringify({ "reaction": reaction });

    $.ajax({
        type: "POST",
        url: "http://www.unicefenjij.nu/Webservices/Unicefenjij.asmx/SendReaction",
        contentType: "application/json; charset=utf-8",
        data: jsonData,
        dataType: "json",
        success: SendReaction_OnSuccess,
        error: OnError
    });
}

function SendReaction_OnSuccess(data, textStatus, XMLHttpRequest) {

    $("#placeReactionPane").hide();
    $("#ReactionThankYou").show();
}


function SendQuestion() {

    if (!validateEmail($('#txtAskEmail').val()) ||
        $('#txtAskQuestion').val() == "" ||
        $('#txtAskName').val() == "" ||
        $('#txtAskEmail').val() == "" ||
        $('#txtAskAge').val() == "") {
        $('#AskFormError').fadeIn();
        return false;
    }

    $('#AskFormError').fadeOut();

    var question = new Object();

    question.Content = $('#txtAskQuestion').val();
    question.NameVisitor = $('#txtAskName').val();
    question.MailAddress = $('#txtAskEmail').val();
    question.Age = $('#txtAskAge').val();

    var jsonData = JSON.stringify({ "question": question });

    $.ajax({
        type: "POST",
        url: "http://www.unicefenjij.nu/Webservices/Unicefenjij.asmx/SendQuestion",
        contentType: "application/json; charset=utf-8",
        data: jsonData,
        dataType: "json",
        success: SendQuestion_OnSuccess,
        error: OnError
    });
}

function SendQuestion_OnSuccess(data, textStatus, XMLHttpRequest) {
    $("#AskForm").hide();
    $("#AskThankYou").show();
}


function SendNotOkay(reactionNodeId) {

    var reaction = new Object();
    reaction.NodeId = reactionNodeId;

    var jsonData = JSON.stringify({ "reaction": reaction });

    $.ajax({
        type: "POST",
        url: "http://www.unicefenjij.nu/Webservices/Unicefenjij.asmx/SendNotOkay",
        contentType: "application/json; charset=utf-8",
        data: jsonData,
        dataType: "json",
        success: SendNotOkay_OnSuccess,
        error: OnError
    });

    return false;
}

function SendNotOkay_OnSuccess(data, textStatus, XMLHttpRequest) {
    alert("Dank je wel voor deze melding! Wij zullen deze reactie beoordelen.");
}



function ShowRandomReaction() {
    $("#panelEnJij").fadeOut(250, function () {
        $("#panelEnJij").empty();
        var container = $(document.createElement('div'));
        $("#panelEnJij").append(container);
        container.load(getWebserviceURL() + "utilitypages/randomreaction.aspx", null, randomReaction_loadHandler);
    });
}

function randomReaction_loadHandler() {
    $("#panelEnJij").fadeIn(250);
}

function ShowRandomActieVanAnderen() {

    $("#panelEnJij").fadeOut(250, function () {
        $("#panelEnJij").empty();
        var container = $(document.createElement('div'));
        $("#panelEnJij").append(container);

        var d = new Date();
        var forceRefresh = d.getMilliseconds();
        container.load(getWebserviceURL() + "/utilitypages/randomactievananderen.aspx?forceRefresh=" + forceRefresh, null, showRandomActieVanAnderen_loadHandler);
    });

}

function showRandomActieVanAnderen_loadHandler() {

    $("#actiesVanAnderen").attr("href", $(".panelEnJij").attr("href"));
    $("#panelEnJij").fadeIn(250);
}


function ShowLatestActivatieActieSubmissions() {

    $("#panelActivatieActie").fadeOut(250, function () {
        $("#panelActivatieActie").empty();
        var container = $(document.createElement('div'));
        $("#panelActivatieActie").append(container);

        var d = new Date();
        var forceRefresh = d.getMilliseconds();
        container.load(getWebserviceURL() + "/utilitypages/latestactivatieactiesubmissions.aspx?forceRefresh=" + forceRefresh, null, showLatestActivatieActieSubmissions_loadHandler);
    });

}

function showLatestActivatieActieSubmissions_loadHandler() {
    $("#actiesVanAnderen").attr("href", $(".panelActivatieActie").attr("href"));
    $("#panelActivatieActie").fadeIn(250);
}



function SendLike(reactionNodeId) {

    var reaction = new Object();
    reaction.NodeId = reactionNodeId;

    var jsonData = JSON.stringify({ "reaction": reaction });

    $.ajax({
        type: "POST",
        url: "http://www.unicefenjij.nu/Webservices/Unicefenjij.asmx/SendLike",
        contentType: "application/json; charset=utf-8",
        data: jsonData,
        dataType: "json",
        success: function () { SendLike_OnSuccess(reactionNodeId); },
        error: OnError
    });

    return false;
}

function SendLike_OnSuccess(relId) {

    var button = $(".likeButton[rel=" + relId + "]");
    var value = parseInt(button.html());
    button.html(value + 1);
}

function SendDislike(reactionNodeId) {

    var reaction = new Object();
    reaction.NodeId = reactionNodeId;

    var jsonData = JSON.stringify({ "reaction": reaction });

    $.ajax({
        type: "POST",
        url: "http://www.unicefenjij.nu/Webservices/Unicefenjij.asmx/SendDislike",
        contentType: "application/json; charset=utf-8",
        data: jsonData,
        dataType: "json",
        success: function () { SendDislike_OnSuccess(reactionNodeId); },
        error: OnError
    });

    return false;
}

function SendDislike_OnSuccess(relId) {

    var button = $(".dislikeButton[rel=" + relId + "]");
    var value = parseInt(button.html());
    button.html(value + 1);
}


