var domLoaded = false;
/**
 * Check periodically if dom has been loaded
 */
function domReady(nodeId){
    this.n = typeof(this.n)=='undefined'?0:this.n+=1;
    var scriptTimeout = 1000;
    if(document.getElementById(nodeId)!=null){
        domLoaded = true;
        init();
        //window.status = 'DOM loaded';
    }else if(this.n < scriptTimeout){
        window.status = window.status + '.';
        setTimeout(function(){domReady(nodeId)}, 50);
    }
}
window.onload = function(){
    domReady('DOMReady');
}
/**
 * Init script that is run after page loading is finished.
 * @return
 */
function init(){
    Element.extend(window.document);
    window.document.observe('mousemove',
        function(e){
            if($('RightButton')) {
                $('RightButton').style.left=e.clientX+'px';
                $('RightButton').style.top=e.clientY+'px';
            }
        }
    );
}
/**
 * askConfirmation() displays confirmation dialog
 */
function askConfirmation(message, url) {
    if (confirm(message)) {
        window.location = url;
    }
    return;
}
/**
 * Swaps CSS class name
 */
function swapClass(obj, className) {
    obj.className = className;
    return;
}
/**
 * Checks all checkboxes with that name
 */
function checkAllByName(theName) {
    var list = document.getElementsByName(theName);
    for (i = 0; i < list.length; i++) {
        list[i].checked = !list[i].checked;
    }
}
var contextEditor = null;
var timerId = 0;
function createNewContextEditor(sender, id, appWebPath) {
    if (ContextEditor.prototype.isPrototypeOf(contextEditor)
            && contextEditor.id != id) {
        destroyContextEditor();
        clearTimeout(timerId);
    }
    if (!ContextEditor.prototype.isPrototypeOf(contextEditor)) {
        contextEditor = new ContextEditor(sender, id, appWebPath);
        contextEditor.show();
        contextEditor.container.onmouseout = destroySlowly;
    }
}
function destroyContextEditor() {
    if (!contextEditor.mouseIsInside(mouseCoords)) {
        contextEditor.destroy();
        contextEditor = null;
    }
    return;
}
function destroySlowly() {
    timerId = setTimeout('destroyContextEditor()', 1000);
}
/**
 * Xallery image context editor
 */
function ContextEditor(sender, id, appWebPath) {
    this.contextItems = [ [ 'Edit image', 'editimage.html' ],
            [ 'Remove image', 'removeimage.html' ] ];
    this.id = id;
    this.sender = sender;
    this.appWebPath = appWebPath;
}
ContextEditor.prototype = {
    id :null,
    sender :null,
    container :null,
    timerId :null,
    top :0,
    left :0,
    right :0,
    bottom :0,
    appWebPath :null,
    contextItems : []
};
ContextEditor.prototype.show = function showEditor() {
    coords = getAbsoluteXY(this.sender);
    var div = document.createElement('div');
    div.id = 'contextcontainer' + this.id;
    div.className = 'contextContainer';
    div.style.left = coords[0] + 5 + 'px';
    div.style.top = coords[1] - 50 + 'px';
    div.style.visibility = 'visible';

    for (i = 0; i < this.contextItems.length; i++) {
        var itemDiv = document.createElement('div');
        var link = document.createElement('a');
        link.innerHTML = this.contextItems[i][0];
        link.setAttribute('href',
                "javascript:askConfirmation('Kas oled kindel?', '"
                        + this.contextItems[i][1] + '?id=' + this.id + "')");
        itemDiv.appendChild(link);
        itemDiv.className = 'contextItem';
        itemDiv.onmouseover = clrTimeout(timerId);
        div.appendChild(itemDiv);
    }
    this.container = document.body.appendChild(div);
    coords = getAbsoluteXY(this.container);
    this.left = coords[0];
    this.top = coords[1];
    this.bottom = this.top + this.container.offsetHeight;
    this.right = this.left + this.container.offsetWidth;
}
ContextEditor.prototype.mouseIsInside = function mouseIsInsideArea(mouseCoords) {
    mouseX = mouseCoords[0];
    mouseY = mouseCoords[1];
    return (mouseX >= this.left && mouseY >= this.top && mouseY <= this.bottom && mouseX <= this.right);
}

ContextEditor.prototype.destroy = function destroyEditor() {
    document.body.removeChild(this.container);
}

function clrTimeout(timerId) {
    clearTimeout(timerId);
}
function getAbsoluteXY(object) {
    var x = 0;
    var y = 0;
    do {
        x += object.offsetLeft || 0;
        y += object.offsetTop || 0;
        object = object.offsetParent;
    } while (object);
    return [ x, y ];
}
/**
 * Gets mouse coordinates
 */
var mouseCoords = [ 0, 0 ];
document.onmousemove = getMouse;

function getMouse(e) {
    var mx, my;
    if (document.all) {
        mx = event.clientX;
        my = event.clientY;
        ie = true;
    } else {
        mx = e.pageX;
        my = e.pageY;
    }
    mouseCoords[0] = mx;
    mouseCoords[1] = my;
    return mouseCoords;
}

function hideObject(o) {
    o.style.visibility = 'hidden';
}
var leftOverlay = null;
var rightOverlay = null;
function initOverlays(width, height, left, top) {
    if (leftOverlay == null || rightOverlay == null) {
        leftOverlay = document.getElementById('leftOverlay');
        rightOverlay = document.getElementById('rightOverlay');
        leftOverlay.style.width = parseInt(width / 2) + 'px';
        leftOverlay.style.height = height + 'px';
        rightOverlay.style.width = parseInt(width / 2) + 'px';
        rightOverlay.style.height = height + 'px';
        leftOverlay.style.left = left + 'px';
        leftOverlay.style.top = top + 'px';
        rightOverlay.style.left = parseInt(left + (width / 2)) + 'px';
        rightOverlay.style.top = top + 'px';
    }


}
function showOverlay(sender, imageId) {
    var image = $(imageId);
    var imageCoords = getAbsoluteXY(image);
    var mouseLeft = mouseCoords[0];
    var mouseTop = mouseCoords[1];
    var imageLeft = imageCoords[0];
    var imageTop = imageCoords[1];
    var imageWidth = image.getAttribute('width');
    var imageHeight = image.getAttribute('height');
    initOverlays(imageWidth, imageHeight, imageCoords[0], imageCoords[1]);
    if (mouseLeft > (imageLeft + (imageWidth / 2))) {
        rightOverlay.style.top = imageTop+(imageHeight/2)-35+'px';
        rightOverlay.style.visibility = 'visible';
        leftOverlay.style.visibility = 'hidden';
    } else {
        leftOverlay.style.top = imageTop+(imageHeight/2)-35+'px';
        rightOverlay.style.visibility = 'hidden';
        leftOverlay.style.visibility = 'visible';
    }
}

/**
 * Composes e-mail address so that adds
 *
 * @-sign between str1 and str2
 */
function composeEmail(str1, str2) {
    var address = 'mailto:' + str1 + '@' + str2;
    window.location = address;
}

function displaySignature(theNewUrl) {
    try {
        var el = document.getElementById('exampleImage');
        if (el) {
            el.src = theNewUrl;
        }
    } catch (e) {

    }
}
/**
 * Displays popup image over existing thumbnail
 */
function showPopupImage(theId, theImagePath) {
    try {
        var containerElement = document.getElementById(theId);
        var div = containerElement.appendChild(document.createElement('div'));
        div.setAttribute('class', 'popupImageContainer');
        div.setAttribute('id', theId + 'd');
        div.style.left = mouseCoords[0] + 'px';
        div.style.top = mouseCoords[1] + 'px';

        var img = document.createElement('img');
        img.setAttribute('src', theImagePath);
        img.setAttribute('class', 'popupImage');
        div.appendChild(img);

        var shadow = document.createElement('div');
        shadow.setAttribute('class', 'popupImageShadow');
        div.appendChild(shadow);

        div.style.visibility = 'visible';
    } catch (e) {
        alert(e);
    }
}
/**
 * Destroys popup image object
 */
function destroyPopupImage(theId) {
    try {
        var containerElement = document.getElementById(theId);
        var divElement = document.getElementById(theId + 'd');
        containerElement.removeChild(divElement);
    } catch (e) {
        alert(e);
    }
}
/**
 * Displays progress bar
 */
var progressIndicator;
function showProgessIndicator(theContainerId) {
    progressIndicator = document.getElementById('progressIndicator');
    if (progressIndicator == null) {
        progressIndicator = document.createElement('div');
        progressIndicator.setAttribute('id', 'progressIndicator');
        progressIndicator.innerHTML = 'Test';
        var container = document.getElementById(theContainerId);
        container.appendChild(progressIndicator);
    }
    return;
}
function getFormData(mode) {

    var formElements = $("form1").getInputs();
    var objectHash = $H();
    // siin lisad
    formElements.each( function(item) {
        if (item.type != "button" && item.value != "") {
            if (item.type == "checkbox" || item.type == "radio") {
                if (item.checked == true) {
                    objectHash.set(item.name, item.value);
                }
            } else {
                objectHash.set(item.name, item.value);
            }

        }

        // siin lisad kõik väljad objecthHashi
            // vata prototype näiteid
            // /objectHash.set/(item.name, item.value);
            // midagi sellist
        });

    var selects = $A(document.getElementsByTagName('select'));
    selects.each( function(item2) {
        value2 = $F(item2);
        objectHash.set(item2.name, value2);

    });
    // siin lisad selectid
    // kõigi selektide massiivi saad ka kätte prototype vahendeid kasutades
    // itereerid nendest samuti läbi kui väljadest
    // ja loopis lisad väärtused hashi
    // saadad ära JSON stringi
    // serveri poole otsid või teed JSON deserializeri

    // return;
    /*
    * var eles = $("form1").serialize(true); for(x in formElements){ //eles =
    * eles+formElements[x].name+"="+formElements[x].value+","; } eles =
    * eles+"&price="+document.getElementById('NetPrice').innerHTML;
    */
    if (mode != "save" && mode != "pdf") {
        xajax_calcArea(objectHash.toJSON());
        return;
    } else {
        if (mode == "pdf") {
            xajax_createPdf(objectHash.toJSON());
            return;
        } else {

            xajax_saveOffer(objectHash.toJSON());

            return;
        }
    }

}

function addDownloadButton(i) {
    var container = document.getElementById('ButtonContainer');
    var DownloadButton = document.createElement("INPUT");
    if (document.getElementById('DownloadButton') == null) {
        DownloadButton.setAttribute('type', 'button');
        DownloadButton.setAttribute('onclick',
                'window.location = "download.html?id=' + i + '"');
        DownloadButton.setAttribute('class', 'button');
        DownloadButton.setAttribute('id', 'DownloadButton');
        DownloadButton.setAttribute('value', 'Lae PDF alla');
        container.innerHTML += "&nbsp;&raquo;&nbsp;";
        container.appendChild(DownloadButton);
    }
}

function addRow(val1, val2, val3, val4, val5, val6) {
    // newRow = document.createElement('tr');
    // newRow.innerHTML = "lambad rsk!";
    var tbody = document.getElementById("ItemListContainer").tBodies[0];
    var row = document.createElement("TR");
    row.setAttribute('id', val6);
    var cell1 = document.createElement("TD");
    cell1.innerHTML = val1;
    cell1.setAttribute('class', 'col1');
    var cell2 = document.createElement("TD");
    cell2.innerHTML = val2;
    cell2.setAttribute('class', 'col2 borderLeft');
    var cell3 = document.createElement("TD");
    cell3.innerHTML = val3;
    cell3.setAttribute('class', 'col3 borderLeft');
    var cell4 = document.createElement("TD");
    cell4.innerHTML = val4;
    cell4.setAttribute('class', 'col4 borderLeft');
    var cell5 = document.createElement("TD");
    cell5.innerHTML = val5;
    cell5.setAttribute('class', 'col5 borderLeft');
    var cell6 = document.createElement("TD");
    cell6.innerHTML = '<a href="javascript:delRow(' + val6 + ')">X</a>';
    cell6.setAttribute('class', 'col6 borderLeft');
    row.appendChild(cell1);
    row.appendChild(cell2);
    row.appendChild(cell3);
    row.appendChild(cell4);
    row.appendChild(cell5);
    row.appendChild(cell6);
    tbody.appendChild(row);
    // document.insertBefore(newRow, oldRow);

}
function delRow(row2) {
    getFormData();
    xajax_deleteOfferItem(row2);
    var tbody = document.getElementById("ItemListContainer").tBodies[0];
    // var rows = (tbody.getElementsByTagName("tr").length)-1;
    var row = document.getElementById(row2);
    tbody.removeChild(row);
}
function validate() {
    var formElements = $("form1").getInputs();
    var error = 0;
    formElements.each( function(item) {
        if (item.type != "button" && item.type!='hidden') {
            if( item.type != "checkbox" || item.type != "radio") {
                if(item.name != "Phone" && item.name != "Email") {
                    if (item.value == "") {
                        error = 1;
                    }
                }
            }

        }
    });
    if (error == 1) {
        alert("Kõik tekstiväljad peavad olema täidetud!");
        return false;
    } else {
        getFormData('save');
    }
    return true;
}
function disableRadio(mode) {

    var radios = $("form1").getInputs('radio', mode);
    // radios = $('GlassType');
    // alert(radios[0].disabled);
    $('GlassType').invoke('disable');
    radios.invoke(radios[0].disabled ? 'enable' : 'disable');
    // $('GlassType')[$('GlassType').disabled ? 'enable' : 'disable']();
    // alert($('GlassType').disabled);
    // $('GlassType').disable;
    radios[0].disabled = !radios[0].disabled;
    // alert(radios[0].disabled);

}
