// This example is based on the previous ('4-test-fly.html')
// sample and (also) shows a way to handle multiple INPUT
// fields with a single vkeyboard. The only difference is
// that now we don't need fields' id's: script finds and
// enumerates all INPUTs automatically.

// 'source' is the field which is currently focused:
var source = null, insertionS = 0, insertionE = 0;

var vkb = null;

var userstr = navigator.userAgent.toLowerCase();
var safari = (userstr.indexOf('applewebkit') != -1);
var gecko  = (userstr.indexOf('gecko') != -1) && !safari;
var standr = gecko || window.opera || safari;
var kioskTimmerStamp = new Date();
var currentTimeoutSeconds = (((kioskTimmerStamp.getMinutes()*60) + kioskTimmerStamp.getSeconds())+orderTimeoutLength);;
var ns = (navigator.appName.indexOf("Netscape") != -1);
var d = document;
var px = document.layers ? "" : "px";
var orderTimeoutLength = 30;

setup_event(window, "load", kioskSetup);
setup_event(document, "mousemove", resetKioskTimmerStamp);

// This function retrieves the source element
// for the given event object:
function get_event_source(e){
    var event = e || window.event;
    return event.srcElement || event.target;
}

// This function binds 'handler' function to the 
// 'eventType' event of the 'elem' element:
function setup_event(elem, eventType, handler){
    return (elem.attachEvent) ? elem.attachEvent("on" + eventType, handler) : ((elem.addEventListener) ? elem.addEventListener(eventType, handler, false) : false);
}

// By focusing the INPUT field we set the 'source'
// to the newly focused field:
function focus_keyboard(e){
    source = get_event_source(e);
}

// By "registering" the field we bind 'focus_keyboard'
// function to 'focus' event of the given INPUT field:
function register_field(element){
    setup_event(element, "focus", focus_keyboard);
}

function resetKioskTimmerStamp(){
    currentTimeoutSeconds = (((kioskTimmerStamp.getMinutes()*60) + kioskTimmerStamp.getSeconds())+orderTimeoutLength);
}

function checkForKioskTimeout(){
    kioskTimmerStamp = new Date();
    var timeNowSeconds = (((kioskTimmerStamp.getMinutes()*60) + kioskTimmerStamp.getSeconds()));
    var timeoutAlertElement = document.getElementById('kioskTimer');
    var timeDifference = currentTimeoutSeconds - timeNowSeconds
    if( timeDifference == 10 ){
        if(vkb){
            vkb.Show(false);
        }
    }
    if( timeDifference < 11 ){
        timeoutAlertElement.innerHTML =  "<br>Your order is going to be canceled due to inactivity in " + (timeDifference) + ".<br>&nbsp;";
        timeoutAlertElement.style.display = "block";
    }else{
            timeoutAlertElement.innerHTML =  "";
        timeoutAlertElement.style.display = "none";
    }
    if( timeDifference < 1 ){
        window.location = "http://www.seamlessweb.com/kiosk.htm";
    }
    setTimeout(checkForKioskTimeout, 500);
}

function kioskSetup(){
    if( document.cookie.indexOf("kiosk") > -1) {
        if(location.href.toLowerCase().indexOf("logout") > -1){
            clearSeamlessCookies();
        }
        attachNeededElements();
        textBoxSetup();
        textareaBoxSetup();
        selectBoxSetup();
        if(typeof(skipTimeout) == "undefined" || !skipTimeout){
            checkForKioskTimeout();
	}
	if(typeof(populateKioskAddress) != "undefined" && populateKioskAddress){
            useKioskAddress();
	}
    }
}

function useKioskAddress(){
    if( document.cookie.indexOf("kioskAddress") > -1 && document.cookie.indexOf("ConsumerAddress") < 0) {
        var cookieParm = new Array();
        var cookie = getCookie("kioskAddress");
        var parms = cookie.split('&');
        for (var i=0; i < parms.length; i++) {
            var pos = parms[i].indexOf('=');
            if (pos > 0) {
                var key = parms[i].substring(0,pos);
                var val = parms[i].substring(pos+1);
                cookieParm[key] = val;
            }
        }
        document.getElementById("street").value = cookieParm["street"];
        document.getElementById("buildingFloor").value = cookieParm["buildingFloor"];
        document.getElementById("zipCode").value = cookieParm["zipCode"];
    }
}

function attachNeededElements(){
    var keyBoardElement = document.createElement("<DIV id='keyboard' />");
    var timeoutAlertElement = document.createElement("<DIV id='kioskTimer' />");
    var bodyElement = document.getElementsByTagName("BODY");
    bodyElement[0].appendChild(keyBoardElement);
    bodyElement[0].appendChild(timeoutAlertElement)
    timeoutAlertElement.style.width = "100%";
    timeoutAlertElement.style.position = "absolute";
    timeoutAlertElement.style.background = "#ff4";
    timeoutAlertElement.style.fontSize = "20px";
    timeoutAlertElement.style.display = "none";
    timeoutAlertElement.style.textAlign = "center";
    JSFX_FloatDiv("kioskTimer", 0, -85).flt();
}

function selectBoxSetup(){    
    var dropDowns = document.getElementsByTagName("SELECT");
    if(dropDowns.length > 0){
        for ( keyVar in dropDowns ) {
            if (typeof(dropDowns[keyVar]) == "object"){
                dropDowns[keyVar].style.fontSize = "20px";
                if(dropDowns[keyVar].id == "deliveryMethod"){ dropDowns[keyVar].style.width = "10em"};
            }
        }
    }
}

function textBoxSetup(){
    var textInputs = document.getElementsByTagName("INPUT");
    if(textInputs.length > 0){
        for ( keyVar in textInputs ) {
            if (typeof(textInputs[keyVar]) == "object"){
                if( textInputs[keyVar].type == "text" || textInputs[keyVar].type == "password" ){
                    register_field(textInputs[keyVar]);
                    setup_event(textInputs[keyVar], "focus", focus_keyboard);
                    setup_event(textInputs[keyVar], "focus", function(){showKeyboard(window.event.srcElement);});
                }
            }
        }
    }
}

function textareaBoxSetup(){
    var textAreaInputs = document.getElementsByTagName("TEXTAREA");
    if(textAreaInputs.length > 0){
        for ( keyVar in textAreaInputs ) {
            if (typeof(textAreaInputs[keyVar]) == "object"){
                register_field(textAreaInputs[keyVar]);
                setup_event(textAreaInputs[keyVar], "focus", focus_keyboard);
                setup_event(textAreaInputs[keyVar], "focus", function(){showKeyboard(window.event.srcElement);});
            }
        }
    }
}

function JSFX_FloatDiv(id, sx, sy)
{
    var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
    window[id + "_obj"] = el;
    if(d.layers)el.style=el;
    el.cx = el.sx = sx;
    el.cy = el.sy = sy;
    el.sP=function(x,y){this.style.left=x+px;this.style.top=y+px;};
    el.flt=function(){
        var pX, pY;
        pX = (this.sx >= 0) ? 0 : ns ? innerWidth : 
        d.documentElement && d.documentElement.clientWidth ? 
        d.documentElement.clientWidth : d.body.clientWidth;
        pY = ns ? pageYOffset : d.documentElement && d.documentElement.scrollTop ? d.documentElement.scrollTop : d.body.scrollTop;
        if(this.sy<0){
            pY += ns ? innerHeight : d.documentElement && d.documentElement.clientHeight ? d.documentElement.clientHeight : d.body.clientHeight;
	}
        this.cx += (pX + this.sx - this.cx);
        this.cy += (pY + this.sy - this.cy);
        this.sP(this.cx, this.cy);
        setTimeout(this.id + "_obj.flt()", 40);
    }
    return el;
}

function showKeyboard(element){
    // Note: all parameters, starting with 3rd, in the following
    // expression are equal to the default parameters for the
    // VKeyboard object. The only exception is 18th parameter
    // (flash switch), which is false by default.
    if(!vkb){
        var id = "keyboard";
        var keyboardDiv = d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
        keyboardDiv.style.width = "100%";
        keyboardDiv.style.position = "absolute";
        keyboardDiv.style.background = "#fff";
    
        vkb = new VKeyboard("keyboard",    // container's id
            keyb_callback, // reference to the callback function
            false,          // create the arrow keys or not? (this and the following params are optional)
            false,          // create up and down arrow keys? 
            false,         // reserved
            false,          // create the numpad or not?
            "",            // font name ("" == system default)
            "28px",        // font size in px
            "#000",        // font color
            "#F00",        // font color for the dead keys
            "#FFF",        // keyboard base background color
            "#FFF",        // keys' background color
            "#DDD",        // background color of switched/selected item
            "#777",        // border color
            "#CCC",        // border/font color of "inactive" key (key with no value/disabled)
            "#FFF",        // background color of "inactive" key (key with no value/disabled)
            "#F77",        // border color of the language selector's cell
            false,          // show key flash on click? (false by default)
            "#CC3300",     // font color during flash
            "#FF9966",     // key background color during flash
            "#CC3300",     // key border color during flash
            false,         // embed VKeyboard into the page?
            true,          // use 1-pixel gap between the keys?
            0);            // index(0-based) of the initial layout
        JSFX_FloatDiv("keyboard", 0, -260).flt();

        // The very 1st (index == 0) field is "focused" by default:
        source = element;
        source.focus();
    }
    else{
        vkb.Show(true)
    }
}

// Advanced callback function:
//
function keyb_callback(ch){
    var val = source.value;

    switch(ch) {
        case "BackSpace":
            if(val.length){
                var span = null;

                if(document.selection){
                    span = document.selection.createRange().duplicate();
                }
                if(span && span.text.length > 0){
                    span.text = "";
                    getCaretPositions(source);
                }else{
                    deleteAtCaret(source);
                }
            }
        break;

        case "<":
            if(insertionS > 0){
                setRange(source, insertionS - 1, insertionE - 1);
            }
        break;

        case ">":
            if(insertionE < val.length)
            setRange(source, insertionS + 1, insertionE + 1);
        break;

        case "/\\":
            if(!standr){
                break;
            }

            var prev  = val.lastIndexOf("\n", insertionS) + 1;
            var pprev = val.lastIndexOf("\n", prev - 2);
            var next  = val.indexOf("\n", insertionS);

            if(next == -1){
                next = val.length;
            }
            var nnext = next - insertionS;

            if(prev > next){
                prev  = val.lastIndexOf("\n", insertionS - 1) + 1;
                pprev = val.lastIndexOf("\n", prev - 2);
            }

            // number of chars in current line to the left of the caret:
            var left = insertionS - prev;

            // length of the prev. line:
            var plen = prev - pprev - 1;

            // number of chars in the prev. line to the right of the caret:
            var right = (plen <= left) ? 1 : (plen - left);

            var change = left + right;
            setRange(source, insertionS - change, insertionE - change);
        break;

        case "\\/":
            if(!standr){
                break;
            }

            var prev  = val.lastIndexOf("\n", insertionS) + 1;
            var next  = val.indexOf("\n", insertionS);
            var pnext = val.indexOf("\n", next + 1);

            if( next == -1){
                next = val.length;
            }
            if(pnext == -1){
                pnext = val.length;
            }

            if(pnext < next){
                pnext = next;
            }

            if(prev > next){
                prev  = val.lastIndexOf("\n", insertionS - 1) + 1;
            }

            // number of chars in current line to the left of the caret:
            var left = insertionS - prev;

            // length of the next line:
            var nlen = pnext - next;

            // number of chars in the next line to the left of the caret:
            var right = (nlen <= left) ? 0 : (nlen - left - 1);

            var change = (next - insertionS) + nlen - right;
            setRange(source, insertionS + change, insertionE + change);
        break;

        default:
            insertAtCaret(source, (ch == "Enter" ? (window.opera ? '\r\n' : '\n') : ch));
    }
}

// This function retrieves the position (in chars, relative to
// the start of the text) of the edit cursor (caret), or, if
// text is selected in the TEXTAREA, the start and end positions
// of the selection.
//
function getCaretPositions(ctrl){
    var CaretPosS = -1, CaretPosE = 0;

    // Mozilla way:
    if(ctrl.selectionStart || (ctrl.selectionStart == '0')){
        CaretPosS = ctrl.selectionStart;
        CaretPosE = ctrl.selectionEnd;

        insertionS = CaretPosS == -1 ? CaretPosE : CaretPosS;
        insertionE = CaretPosE;
    }else if(document.selection && ctrl.createTextRange){
        var start = end = 0;
        try{
            start = Math.abs(document.selection.createRange().moveStart("character", -10000000)); // start

            if (start > 0){
                try{
                    var endReal = Math.abs(ctrl.createTextRange().moveEnd("character", -10000000));

                    var r = document.body.createTextRange();
                    r.moveToElementText(ctrl);
                    var sTest = Math.abs(r.moveStart("character", -10000000));
                    var eTest = Math.abs(r.moveEnd("character", -10000000));

                    if ((ctrl.tagName.toLowerCase() != 'input') && (eTest - endReal == sTest))
                    start -= sTest;
                }catch(err) {}
            }
        }catch (e) {}

        try{
            end = Math.abs(document.selection.createRange().moveEnd("character", -10000000)); // end
            if(end > 0){
                try{
                    var endReal = Math.abs(ctrl.createTextRange().moveEnd("character", -10000000));

                    var r = document.body.createTextRange();
                    r.moveToElementText(ctrl);
                    var sTest = Math.abs(r.moveStart("character", -10000000));
                    var eTest = Math.abs(r.moveEnd("character", -10000000));

                    if ((ctrl.tagName.toLowerCase() != 'input') && (eTest - endReal == sTest)){
                        end -= sTest;
                    }
                }catch(err) {}
            }
        }catch (e) {}

        insertionS = start;
        insertionE = end
    }
}

function setRange(ctrl, start, end){
    if(ctrl.setSelectionRange){ // Standard way (Mozilla, Opera, Safari ...)
        ctrl.setSelectionRange(start, end);
    }else{ // MS IE
        var range;

        try{
            range = ctrl.createTextRange();
        }catch(e){
            try{
                range = document.body.createTextRange();
                range.moveToElementText(ctrl);
            }catch(e){
                range = null;
            }
        }

        if(!range){
            return;
        }

        range.collapse(true);
        range.moveStart("character", start);
        range.moveEnd("character", end - start);
        range.select();
    }

    insertionS = start;
    insertionE = end;
}

function deleteSelection(ctrl){
    if(insertionS == insertionE) return;

    var tmp = (document.selection && !window.opera) ? ctrl.value.replace(/\r/g,"") : ctrl.value;
    ctrl.value = tmp.substring(0, insertionS) + tmp.substring(insertionE, tmp.length);

    setRange(ctrl, insertionS, insertionS);
}

function deleteAtCaret(ctrl){
    // if(insertionE < insertionS) insertionE = insertionS;
    if(insertionS != insertionE){
        deleteSelection(ctrl);
        return;
    }

    if(insertionS == insertionE){
        insertionS = insertionS - 1;
    }

    var tmp = (document.selection && !window.opera) ? ctrl.value.replace(/\r/g,"") : ctrl.value;
    ctrl.value = tmp.substring(0, insertionS) + tmp.substring(insertionE, tmp.length);

    setRange(ctrl, insertionS, insertionS);
}

// This function inserts text at the caret position:
//
function insertAtCaret(ctrl, val){
    if(insertionS != insertionE){
        deleteSelection(ctrl);
    }

    if(gecko && document.createEvent && !window.opera){
        var e = document.createEvent("KeyboardEvent");

        if(e.initKeyEvent && ctrl.dispatchEvent){
            e.initKeyEvent("keypress",        // in DOMString typeArg,
            false,             // in boolean canBubbleArg,
            true,              // in boolean cancelableArg,
            null,              // in nsIDOMAbstractView viewArg, specifies UIEvent.view. This value may be null;
            false,             // in boolean ctrlKeyArg,
            false,             // in boolean altKeyArg,
            false,             // in boolean shiftKeyArg,
            false,             // in boolean metaKeyArg,
            null,              // key code;
            val.charCodeAt(0));// char code.

            ctrl.dispatchEvent(e);
        }
    }else{
        var tmp = (document.selection && !window.opera) ? ctrl.value.replace(/\r/g,"") : ctrl.value;
        ctrl.value = tmp.substring(0, insertionS) + val + tmp.substring(insertionS, tmp.length);
    }

    setRange(ctrl, insertionS + val.length, insertionS + val.length);
}

function getCookie(c_name){
    if (document.cookie.length>0){
        c_start=document.cookie.indexOf(c_name + "=")
        if (c_start!=-1){ 
            c_start=c_start + c_name.length+1 
            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 deleteCookie ( cookie_name ) {
    var cookie_date = new Date ( );  // current date & time
    cookie_date.setTime ( cookie_date.getTime() - 1 );
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function clearSeamlessCookies(){
    document.cookie = "kiosk=true; path=/; domain=seamlessweb.com";
    deleteCookie("Repeatfood-deliveryVisitor");
    deleteCookie("SeamlessWeb");
    deleteCookie("food-delivery");
    deleteCookie("ConsumerAddress");
    if( document.cookie.indexOf("kioskAddress") < 0) {
        var qsParm = new Array();
        var query = window.location.search.substring(1);
        if(query.length > 0){
            document.cookie = "kioskAddress = " + unescape(query) + "; path=/; domain=seamlessweb.com";
        }
    }
}