/**
 * Hold information of ads to puti in  each of the boards
 */
var boardsModel = undefined;

/**
 * This array holds coupls where first item is board-Id and second is related doc.
 * The simulation uses this array for accessing document object of board on which we
 * simulate and then reload after setting the simulation data.
 *
 * @param e
 * @see simulateAdShow
 */
var boardsDocs = new Array();

/**
 * Flag for indicating if mallconnect applet was already loaded.
 */
var mallconnectLoaded = false;

/**
 * Const width of ad-spec div
 */
var adSpecDivWidth = 150;

/**
 * This method is invoked once mall.html is loaded
 */
function loadBoardsSettings() {
    requestBoardsSettings();
}

function requestBoardsSettings() {
    //load ads xml files
    rhzUtil.ajaxObj.onreadystatechange = callbackBoardsSettings;
    var url = 'http://' + location.hostname + "/script/mall/ads_settings.xml"
    rhzUtil.ajaxObj.open("GET", url, true);
    rhzUtil.ajaxObj.send(null);
    return true;
}


/**
 * Callback that is responsible for receiving boardsModel for setting ads
 */
function callbackBoardsSettings() {
    if (rhzUtil.ajaxObj.readyState == 4) {
        boardsModel = rhzUtil.ajaxObj.responseXML.documentElement;
    }
}

/**
 * This method is invoked from within the Mall-Connect Applt to indicate
 * the page that applet was loaded.
 */
function mallConnectLoaded() {
    try {

        //enable chat button
        document.getElementById("btn-send").disabled = false;

        //prepare chat clinet name from cookie if exist else use the default name
        var mallConnect = document.getElementById("mallconnect");
        var clientName = setClientNameFromCookie(mallConnect.getClientName());
        mallConnect.setClientName(clientName);
        mallconnectLoaded = true;
    } catch(exp) {
        alert("Fail to prepare Mall-Connect " + exp.message);
    }
}

/**
 * populate board ads, set label of active board and prepare chat data for
 * currently selected board.
 * <p/>
 * If boards data was not yet initialized upon calling this function board data
 * is request and document is reloaded within 3 seconds let boards data to load. 
 *
 * @param boardId
 * @param boardDoc
 */
function prepareActiveBoard(boardId, boardDoc) {
    if (boardsModel == undefined) {
        requestBoardsSettings();
        setTimeout("location.reload()", 3000);

    } else {
        populateAds(boardId, boardDoc)
        document.getElementById("room-label").innerHTML = boardId;
        var mallConnect = document.getElementById("mallconnect");
        if (mallConnect != undefined && mallconnectLoaded) {
            mallConnect.setActiveRoomId(boardId);
            prepareChatData(boardId);
        }
    }
}

/**
 * Callback method that inform JavaScript with data need to be updated
 * with corresponding to room.
 *
 * @param mode working mode
 * @param roomId Id ofroom to update
 * @param arg1 argument
 */
function roomCallback(mode, roomId, arg1, arg2, arg3) {
    try {
        if (mode == "msg-client-changed-room") {
            updateClientsList(roomId, arg1);
        } else if (mode == "msg-chat-post") {
            addChatMessage(roomId, arg1, arg2);
        } else if (mode == "msg-client-connected") {
            var clientId = arg1;
            clientConnected(clientId);
        } else if (mode == "msg-client-disconnected") {
            clientDisconnected(roomId, arg1);
        } else if (mode == "msg-client-ping") {
            updateClientsList(roomId, arg1, null, arg2);
        }
    } catch(exp) {
        alert("Fail to handle roomCallback operation '" + mode + "'  Exception message: " + exp.description);
    }
}


/**
 * Handle the "add-message" mode of "roomCallback" function
 * @param roomId
 * @param arg1
 */
function addChatMessage(activeRoomId, msgRoomId, arg1) {
    if (activeRoomId == msgRoomId) {
        var jsonObj = eval('(' + arg1 + ')');
        addLineToChat(jsonObj.chatitem);
    }

}

/**
 * if client is in the same room as where client was moved to we rebuild
 * the list of clients for this room
 * @param activeRoomId the active room of thsi client
 * @param newRoomId the new reported room
 */
function updateClientsList(activeRoomId, newRoomId) {
    if (activeRoomId == newRoomId) {

        var clientsEm = document.getElementById("clients-list");
        var len = clientsEm.children.length;
        for (var i = len - 1; i >= 0; i--) {
            clientsEm.removeChild(clientsEm.children[i]);
        }

        var jsonText = mallconnect.getClientsModelAsJSON(newRoomId);
        var jsonObj = eval('(' + jsonText + ')');

        var item;
        var clients = jsonObj.clients;
        for (item in clients) {
            var option = document.createElement("option");
            option.value = clients[item].client_id;
            option.text = clients[item].client_name;
            try {
                clientsEm.add(option, null); // standards compliant
            }
            catch(ex) {
                clientsEm.add(option); // IE only
            }
        }
    }

    //update the realtime rating of the room
    updateRoomRating();
}


/**
 * 
 * Update 'room-rating' table with updated data about number of clients in each room
 */
function updateRoomRating() {
    var mallConnect = document.getElementById("mallconnect");
    var jsonText = mallConnect.getRoomsRatingModelAsJSON();
    var jsonObj = eval('(' + jsonText + ')');


    var ratingTable = document.getElementById("room-rating");
    var len = ratingTable.children.length;
    for (var i = len - 1; i >= 0; i--) {
        ratingTable.removeChild(ratingTable.children[i]);
    }

    var item;
    var data = jsonObj.data;
    var r=0;
    for (item in data) {
        var numClients = data[item].num_clients;

        ratingTable.insertRow(r);
        var rowEm = ratingTable.rows[r];
        r++;
        
        var td1Em = document.createElement("td");
        td1Em.innerHTML = item;
        var td2Em = document.createElement("td");
        td2Em.innerHTML = numClients;

        rowEm.appendChild(td1Em);
        rowEm.appendChild(td2Em);

        //update number of clients on board tab
        var menuItem = document.getElementById("mi_" + item);
        if (menuItem != undefined) {
            var txtEm = menuItem.innerHTML;
            var inx1 = txtEm.indexOf("(");
            var inx2 = txtEm.indexOf(")");
            var newTitle = txtEm.substring(0, inx1 + 1) + numClients + txtEm.substring(inx2);
            menuItem.innerHTML = newTitle;
        }


    }
}


/**
 * Update chat text with current data
 */
function prepareChatData(roomId) {
    //first reset current chat data
    var txtDiscussion = document.getElementById("chat-discussion");
    txtDiscussion.value = "";

    /*var chatTable = window.frames["chatframe"].document.getElementById("chat-data");
    var len = chatTable.children.length;
    for (var i = len - 1; i >= 0; i--) {
        chatTable.removeChild(chatTable.children[i]);
    }*/

    //set the data for thecurrent room
    var mallConnect = document.getElementById("mallconnect");
    var chatData = mallConnect.getChatModelAsJSON(roomId);
    var jsonObj = eval('(' + chatData + ')');
    var item;
    var chat = jsonObj.chat;
    for (item in chat) {
        addLineToChat(chat[item]);
    }
}

/**
 * Post chat message
 */
function postChatMessage() {
    var msg = document.getElementById("chat-message").value;
    var mallConnect = document.getElementById("mallconnect");
    mallConnect.postChatMessage(msg);
}

/**
 * Add single line into chat-data table
 * @param chatitem
 */
function addLineToChat(chatitem) {

    var clientId = chatitem.client_id;
    var clientName = chatitem.client_name;
    var message = chatitem.message;
    var time = chatitem.created_at;

    //add new table row to chat-data
    /*var chatTable = window.frames["chatframe"].document.getElementById("chat-data");
    var rowEm = document.createElement("tr");
    var tdEm = document.createElement("td");
    tdEm.innerHTML = clientName + " " + time + ": " + message;

    rowEm.appendChild(tdEm);
    chatTable.appendChild(rowEm);*/
    var txtDiscussion = document.getElementById("chat-discussion");
    var newLine = clientName + " " + time + ": " + message + "\n";
    txtDiscussion.value = txtDiscussion.value + newLine;

    //reset chat message in case this is a loopback message
    var mallConnect = document.getElementById("mallconnect");
    if (clientId == mallConnect.getClientId()) {
        document.getElementById("chat-message").value = "";
    }
}


/**
 * When connected client is this client, set the default board - lobby
 * @param clientId
 */
function clientConnected(clientId) {
    //Set the default board to 'lobby' and pocessing will return by callback 'msg-client-changed-room' that will cause room to be initialized
    var mallConnect = document.getElementById("mallconnect");
    if (clientId == mallConnect.getClientId()) {
        prepareActiveBoard("lobby", document);
    }
}

/**
 * The notifciatino about client disconnected is used to remove the client from
 * list of clients, in case that we are no presenting the same room as client was
 * before disconnecting.
 *
 * @param jsonText
 */
function clientDisconnected(activeRoomId, clientRoomId, jsonText) {
    if (activeRoomId == clientRoomId) {
        var jsonObj = eval('(' + jsonText + ')');
        var clientsEm = document.getElementById("clients-list");
        var clientId = jsonObj.client_id;
        for (var i = 0; i < clientsEm.options.length; i++) {
            if (clientsEm.options[i].value == clientId) {
                clientsEm.remove(i);
                return;
            }
        }
    }


}

/**
 * Populate ads in the relevant place
 * @param boardModel
 * @param boardId the Id of the board to be populated
 * @param contentEm the document of the board that holds ad-data containers
 */
function populateAds(boardId, boardDoc) {
    if (boardsModel != undefined && boardsModel != null) {
        addEntryToBoardsDocArray(boardId, boardDoc); //update 'boardsDocs' array

        var boardModel = rhzUtil.getChildModelById(boardsModel, boardId);
        var indexNL = rhzUtil.getModelChildren(boardModel);

        for (var i = 0; i < indexNL.length; i++) {
            try {
                var indexModel = indexNL[i];
                var adData = rhzUtil.getParam(indexModel, "ad-data");
                if (adData == null || adData.length == 0) {
                    adData = "Advertise..."
                }
                var adIndex = indexModel.getAttribute("id");
                var adContainerId = "ad-" + adIndex;
                var adContainer = boardDoc.getElementById(adContainerId);
                var adArticleURL = rhzUtil.getParam(indexModel, "article-url");


                //it is possible that same board is presented by few pages, each as its own indexs
                //therfore we first check if calling page has the relevant index before tring to set ad data
                if (adContainer != null) {
                    adContainer.innerHTML = decodeXmlEntities(adData);
                }

                var adSpec = decodeXmlEntities(rhzUtil.getParam(indexModel, "ad-spec"));
                var speccontainerId = "spec-" + adIndex;
                adContainer = boardDoc.getElementById(speccontainerId);
                if (adContainer != null) {

                    rhzUtil.removeEmChildren(adContainer);
                    var aEm = boardDoc.createElement("a");
                    aEm.href = "javascript:parent.showSpec('" + adSpec + "', '" + adIndex + "', '" + boardId + "')";
                    aEm.style.fontSize = "small";

                    var status;
                    if (rhzUtil.getParam(indexModel, "mark") == null) {
                        status = "'Av'";
                    } else {
                        status = "'Oc'";
                    }

                    var aText = boardDoc.createTextNode("Publish (" + adIndex + "  " + status + ")");
                    aEm.appendChild(aText)
                    adContainer.appendChild(aEm);

                    adContainer.appendChild(boardDoc.createTextNode("  "));

                    if (adArticleURL != null && adArticleURL.length != 0) {
                        aEm = boardDoc.createElement("a");
                        aEm.href = adArticleURL;
                        aEm.target = "_blank";
                        aEm.style.fontSize = "small";
                        aText = boardDoc.createTextNode("Article");
                        aEm.appendChild(aText)
                        adContainer.appendChild(aEm);
                    }


                }
            } catch(exp) {
                window.status = exp.message;
            }
        }

    }
}


/**
 * Shwo ad specification
 *
 * @param specData spec data
 * @param adIndex ad index
 */
function showSpec(specData, adIndex, boardId) {
    var specDiv = parent.document.getElementById("ad-spec-div");
    var orderAnchor = rhzUtil.getChildById(specDiv, "order-ad-anchor");
    orderAnchor.href = "javascript:orderAdPlace('" + boardId + "', '" + adIndex + "' )";
    var adSpecText = rhzUtil.getChildById(specDiv, "ad-spec-text");
    adSpecText.innerHTML = adIndex + "<br/>" + specData;
    specDiv.style.left = screen.availWidth / 2 - adSpecDivWidth / 2;
    specDiv.style.top = screen.availHeight / 2;
    specDiv.style.visibility = "visible";
}

/**
 * Hide ad spec
 */
function hideSpec() {
    var specDiv = parent.document.getElementById("ad-spec-div");
    specDiv.style.visibility = "hidden";
}

/**
 * Cal mallconnect applet for loading publisher dashboard for schduling the specific
 * ad Indx
 * @param adIndex
 */
function orderAdPlace(boardId, adIndex) {
    //alert("ordr Ad place : " + adIndex + "  boardId=" + boardId)
    var mallConnect = document.getElementById("mallconnect");
    mallConnect.showAdvertiserView(boardId, adIndex);
    hideSpec();
}

/**
 * This method embed 'data' into 'boardModel' and reload the page so that
 * data will be presented as ad in the specified board/index.
 *
 * @param boardId
 * @param adIndex
 * @param data
 */
function simulateAdShow(boardId, adIndex, data) {
    //boardsModel is a global var at mall.html
    var boardModel = rhzUtil.getChildModelById(boardsModel, boardId);
    var indexModel = rhzUtil.getChildModelById(boardModel, adIndex);
    rhzUtil.setParam(indexModel, "ad-data", data);
    var boardDoc = getDocFromBoardsDocArray(boardId);
    if (boardDoc != null) {
        boardDoc.parent.location.reload()
    }
}

/**
 * Add entry into 'boardsDocs'. The first item of single entry is the boardId
 * and the second item is 'boardDoc'. If boardsDocs already contain this board,
 * override existing data (promiss that array entries are fresh)
 *
 * @param boardId
 * @param boardDoc
 */
function addEntryToBoardsDocArray(boardId, boardDoc) {
    for (var i = 0; i < boardsDocs.length; i += 2) {
        if (boardsDocs[i] == boardId) {
            boardsDocs[i + 1] = boardDoc;
            return;
        }
    }
    boardsDocs.push(boardId);
    boardsDocs.push(boardDoc);
}

/**
 * Get document from 'boardsDocs' array of board with specified Id.
 *
 * @param boardId  board Id
 * @erturn document of related board or 'null' if board was not found on array
 */
function getDocFromBoardsDocArray(boardId) {
    for (var i = 0; i < boardsDocs.length; i += 2) {
        if (boardsDocs[i] == boardId) {
            return boardsDocs[i + 1];
        }
    }
    return null;
}

/**
 * Change client name
 */
function changeClientName() {
    var mallConnect = document.getElementById("mallconnect");
    var txtName = document.getElementById("txt-client-name");
    var clientName = txtName.value;
    mallConnect.changeClientName(clientName);
    setCookie('mall-connect', "client-name:" + clientName, 365);
}


/**
 * Set client name from cookie
 *
 * @return the name that was set, either from cookie or the specified default name
 */
function setClientNameFromCookie(defaultClientName) {
    var txtName = document.getElementById("txt-client-name");
    var ck = getCookie('mall-connect');
    if (ck != null && ck != "") {
        var inx1 = ck.indexOf("client-name:");
        if (inx1 != -1) {
            var ckClientName = ck.substring(inx1 + "client-name:".length);
            txtName.value = ckClientName;
        } else {
            deleteCookie('mall-connect');
            txtName.value = defaultClientName;
        }
    } else {
        txtName.value = defaultClientName;
    }
    return txtName.value;
}


function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
                      ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

/**
 * Delete cookie related with specified domain, by setting its expiry date to the past
 * @param name cookie name
 * @param path path
 * @param domain domain name
 */
function deleteCookie(name, path, domain) {
    if (document.cookie.length > 0) {
        var ck = getCookie('mall-connect');
        if (ck != null && ck != "") {
            document.cookie = name + "=" +
                              ( ( path ) ? ";path=" + path : "") +
                              ( ( domain ) ? ";domain=" + domain : "" ) +
                              ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        }
    }

}

