﻿var chatID = -1;
var refreshID = -1;
var refreshneeded = true;
var autoScroll = true;
var chat_timer = -1;
var refresh_timer = -1;
var deleteID = -1;
var randomSeed = 0;
var room = 1;

$(document).ready(function() {
    $("#delete_chat").dialog({
        bgiframe: true,
        height: 200,
        modal: true,
        draggable: false,
        autoOpen: false,
        resizable: false,
        title: 'Delete Post'
    });
    $("#chat_rules").dialog({
        bgiframe: true,
        height: 600,
        width: 650,
        modal: true,
        draggable: false,
        autoOpen: false,
        resizable: false,
        title: 'Chat Rules'
    });
    $('#autoScroll').click(function() {
        autoScroll = !autoScroll;
        if (autoScroll)
            $('#autoScroll').html("Scroll Off");
        else
            $('#autoScroll').html("Scroll On");
        $('#msg').focus();
    });
    $('#msg').keypress(function(e) {
        var message = get_message();
        if (e.which == 13 && message != "") {
            post_chat(message);
        }
    });
    $('#postchat').click(function() {
        var message = get_message();
        if (message != "") {
            post_chat(message);
        }
    });
    $('#msg').val("");
    refresh_timer = setInterval(refresh, 600000);
    if (readCookie("chat_terms") == "agreed") {
        agree("");
    }
    if (readCookie("room") == "2") {
        switchRoom();
    }
    if (chat_on && readCookie("chat_terms") != "agreed") {
        showRules();
    }

    $('#toggleChat').click(function() {
        if (chat_on)
            createCookie('chatdisabled', "true", 0.9);
        else
            eraseCookie('chatdisabled');
        toggle_chat();
    });
    $('#chat_switch_room').click(function() {
        switchRoom();
    });
});


function toggle_chat() {
    if (chat_on) {
        $('#chatbox,#nochat').toggle();
        clearInterval(chat_timer);
        $('#toggleChatLabel').html('Chat On');
    }
    else {
        chat_ajax();
        refresh();
        $('#chatbox,#nochat').toggle();
        $('#toggleChatLabel').html('Chat Off');
    }
    chat_on = !chat_on;
}

function switchRoom() {
    if (room == 1) {
        room = 2;
        $('#RoomName').html('Chit Chat');
        createCookie("room", "2", 1);
    }
    else {
        room = 1;
        $('#RoomName').html('Rocks Chat');
        createCookie("room", "1", 1);
    }
    $('#shouts').html('<div style="height: 50px; width: 100%; text-align: center; padding-top: 100px;"><img src="Chat/ajax-loader.gif" alt="Please wait.... loading data" /></div>');
    refresh();
}

function post_chat(message) {
    clearInterval(chat_timer);
    randomSeed = Math.floor(Math.random() * 1000);
    $.ajax({
        url: "AJAX/Chat.asmx/makePost",
        type: "POST",
        dataType: "json",
        data: "{'message':'" + message + "','S_chatID':" + chatID + ", 'S_refreshID':" + refreshID + ",'room':" + room + ", 'seed':" + randomSeed + "}",
        contentType: "application/json; charset=utf-8",
        success: function(msg) {
            if (msg['d']['s'] == randomSeed)
                if (msg['d']['t'] > 0)
                process_response(msg['d']);
            $('#msg').val("");
            $('#msg').focus();
        }
    });
    chat_timer = setInterval(chat_ajax, 3000);
}
function chat_ajax() {
    randomSeed = Math.floor(Math.random() * 1000);
    $.ajax({
        url: "AJAX/Chat.asmx/getPosts",
        type: "POST",
        dataType: "json",
        data: "{'S_chatID':" + chatID + ", 'S_refreshID':" + refreshID + ",'room':" + room + ", 'seed':" + randomSeed + "}",
        contentType: "application/json; charset=utf-8",
        success: function(msg) {
            if (msg['d']['s'] == randomSeed) {
                if (msg['d']['t'] > 0)
                    process_response(msg['d']);
            }
        }
    })
}

function process_response(response) {
    var i = 0;
    if (refreshID < response['r'] && !refreshneeded) {
        refreshneeded = true;
        refresh();
        return;
    }
    else if (refreshID < response['r'] && refreshneeded) {
        $('#shouts').html(message(response['m'][i]));
        if (response['m'][i]['id'] > chatID)
            chatID = parseInt(response['m'][i]['id']);
        refreshID = response['r'];
        i++;
	refreshneeded = false;
    }
    for (i; i < response['t']; i++) {
        $('#shouts').append(message(response['m'][i]));
        if (response['m'][i]['id'] > chatID)
            chatID = parseInt(response['m'][i]['id']);
    }
    if (autoScroll && response['t'] > 0)
        $("#shouts").attr('scrollTop', $("#shouts").attr('scrollHeight'));
}

function agree(speed) {
    $('#chatbox .transbox').hide(speed);
    $('#chatbox .welcome_message').hide(speed);
    if (speed != "")
        createCookie("chat_terms", "agreed", 1);
}
function showRules() {
    $('#chatbox .transbox').show();
    $('#chatbox .welcome_message').show();
}
function refresh() {
    clearInterval(chat_timer);
    refreshID = -1;
    refreshID = -1;
    chat_ajax();
    chat_timer = setInterval(chat_ajax, 3000);
}

function get_message() {
    return escape($('#msg').val());
}
function deletepost_confirm() {
    $.ajax({
        url: "AJAX/Chat.asmx/delete",
        type: "POST",
        dataType: "json",
        data: "{'id':'" + deleteID + "','reason': '" + escape($('#delete_reason').val()) + "'}",
        contentType: "application/json; charset=utf-8",
        success: function(msg) {
            refresh();
        }
    });
    $("#delete_chat").dialog("close");
}
function deletepost(id) {
    deleteID = id;
    $('#delete_reason').val('');
    $("#delete_chat").dialog("open");
}
function showterms() {
    $("#chat_rules").dialog('open');
}
function hypenate(s) {
    myregexp = new RegExp(/([^\s-]{5})([^\s-]{5})/);
    return s.replace(myregexp, "$1&shy;$2");
}