/*-----------------------------------------------------------------------------------------------*/
//   Holds some Java-Script functions needed on serveral pages of the audiomagnet application
/*-----------------------------------------------------------------------------------------------*/


// Refresh shopping-basket on page
var refreshShoppingBasket = function (baseURL, msg) {
    new Ajax.Updater('cart_content', baseURL + '/am/musicShopping/renderShoppingBasket', {asynchronous:true,evalScripts:true});
    if (msg) {
        alert("Produkt wurde dem Warenkorb hinzugefügt.");       // TODO needs to be I18N'ed
    }
};

// Show an error message (e.g. when ajax request failed)
var showErrorAlert = function (errorMessage) {
    if (errorMessage && errorMessage.length > 100) {
        errorMessage = errorMessage.substring(0, 100);
    }
    alert("FEHLER:\n" + errorMessage);                        // TODO needs to be I18N'ed
};

// Converts a string into a float number
// returns NaN if string is not a number
var convertToFloat = function (stringValue, onlyPositive) {
    stringValue = stringValue.replace(/,/, '.');
    var number;
    if (!isFinite(stringValue)) {
        return NaN;
    } else {
        number = parseFloat(stringValue);
    }
    if (onlyPositive && number < 0) {
        return NaN;
    }
    return number;
};

// Converts a float into a string
// in the format x,xx  (print ??? if float is NaN)
var convertToString = function (floatValue) {
    var nn = floatValue.toString();

    //correction needed for correct rounding such values as, for example,
//61,5 -> 62 instead of  61
//because the float value of 61,5 is 61,499999... 
    floatValue += 0.0000000001;

    var n = (Math.round(floatValue * 100) / 100).toString();
    if (n == 'NaN') {
        return "???";
    }
    n += (n.indexOf('.') == -1) ? '.00' : '00';
    var p = n.indexOf('.');
    return n.substring(0, p) + ',' + n.substring(p + 1, p + 3);
};


// Helper for setting the JS-TabControl-Component:
// Only set the tab-control if element exists on the page
var setTabControl = function (idName) {
    if ($(idName)) {
        return new Control.Tabs(idName);
    }
    return null
};
var updateSubGenreSearch = function (e, selectId) {
    var rselect = document.getElementById(selectId);
    // Clear all previous options
    var l = rselect.length;
    while (l > 0) {
        l--;
        rselect.remove(l);
    }
    // The response comes back as a bunch-o-JSON
    var subGenres = eval("(" + e.responseText + ")"); // evaluate JSON
    if (subGenres) {
        // Rebuild the select
        for (var i = 0; i <= subGenres.length; i++) {
            var subGenre = subGenres[i];
            var opt = document.createElement('option');
            if (i == 0) {
                opt.text = '--';
                opt.value = '';
            }
            else {
                opt.text = subGenre.name;
                opt.value = subGenre.id;
            }
            try {
                rselect.add(opt, null); // standards compliant; doesn't work in IE
            } catch(ex) {
                rselect.add(opt); // IE only
            }
        }
    }
};
// Functions that is needed for Genre select boxes
var updateSubGenre = function (e, selectId) {
    var rselect = document.getElementById(selectId);
    // Clear all previous options
    var l = rselect.length;
    while (l > 0) {
        l--;
        rselect.remove(l);
    }
    // The response comes back as a bunch-o-JSON
    var subGenres = eval("(" + e.responseText + ")"); // evaluate JSON
    if (subGenres) {
        // Rebuild the select
        for (var i = 0; i < subGenres.length; i++) {
            var subGenre = subGenres[i];
            var opt = document.createElement('option');
            opt.text = subGenre.name;
            opt.value = subGenre.id;
            try {
                rselect.add(opt, null); // standards compliant; doesn't work in IE
            } catch(ex) {
                rselect.add(opt); // IE only
            }
        }
    }
};

//show default value in login fields
var agt = navigator.userAgent.toLowerCase();
var ie = ( document.all ) ? 1 : 0;
if (agt.indexOf("konqueror") != -1 || agt.indexOf("opera") != -1) {
    ie = false;
}

function switchToText(elm, defaultText) {
    if (elm.nodeName.toLowerCase() == "input" && elm.type.toLowerCase() == "password" && elm.value == "") {
        var newElem = document.createElement("input");
        var typeAttrib = document.createAttribute("type");
        typeAttrib.nodeValue = "text";
        newElem.setAttributeNode(typeAttrib);

        var className = elm.className;
        var idVal = elm.id;
        var nameVal = elm.name;
        var maxLen = 20;
        var tabIndex = elm.tabIndex;
        var sizeVal = elm.size;

        if (className && className != "") {
            var classAttrib = document.createAttribute("class");
            classAttrib.nodeValue = elm.className;
            newElem.setAttributeNode(classAttrib);
        }

        if (nameVal && nameVal != "") {
            var nameAttrib = document.createAttribute("name");
            nameAttrib.nodeValue = nameVal;
            newElem.setAttributeNode(nameAttrib);
        }

        if (!idVal || idVal != "") {
            var tmp = new Date();
            idVal = "pwdBox" + tmp.getTime();
        }

        if (idVal && idVal != "") {
            var idAttrib = document.createAttribute("id");
            idAttrib.nodeValue = idVal;
            newElem.setAttributeNode(idAttrib);
        }

        if (maxLen && maxLen != "" && maxLen > 0) {
            var maxLenAttrib = document.createAttribute("maxlength");
            maxLenAttrib.nodeValue = maxLen;
            newElem.setAttributeNode(maxLenAttrib);
        }

        if (tabIndex && tabIndex != "") {
            var tabIndexAttrib = document.createAttribute("tabindex");
            tabIndexAttrib.nodeValue = tabIndex;
            newElem.setAttributeNode(tabIndexAttrib);
        }

        if (sizeVal && sizeVal != "") {
            var sizeValAttrib = document.createAttribute("size");
            sizeValAttrib.nodeValue = sizeVal;
            newElem.setAttributeNode(sizeValAttrib);
        }

        var valueAttrib = document.createAttribute("value");
        valueAttrib.nodeValue = defaultText;
        newElem.setAttributeNode(valueAttrib);

        var focusAttrib = document.createAttribute("onfocus");
        focusAttrib.nodeValue = "switchToPassword(this,'" + defaultText + "');";
        newElem.setAttributeNode(focusAttrib);


        par = elm.parentNode;
        par.replaceChild(newElem, elm);
    }
}
function switchToPassword(elm, defaultText) {
    if (elm.nodeName.toLowerCase() == "input" && elm.type.toLowerCase() == "text") {
        var newElem = document.createElement("input");
        var typeAttrib = document.createAttribute("type");
        typeAttrib.nodeValue = "password";
        newElem.setAttributeNode(typeAttrib);

        var className = elm.className;
        var idVal = elm.id;
        var nameVal = elm.name;
        var maxLen = 50;
        var tabIndex = elm.tabIndex;
        var sizeVal = elm.size;

        if (className && className != "") {
            var classAttrib = document.createAttribute("class");
            classAttrib.nodeValue = elm.className;
            newElem.setAttributeNode(classAttrib);
        }

        if (nameVal && nameVal != "") {
            var nameAttrib = document.createAttribute("name");
            nameAttrib.nodeValue = nameVal;
            newElem.setAttributeNode(nameAttrib);
        }

        if (!idVal || idVal != "") {
            var tmp = new Date()
            idVal = "pwdBox" + tmp.getTime();
        }

        if (idVal && idVal != "") {
            var idAttrib = document.createAttribute("id");
            idAttrib.nodeValue = idVal;
            newElem.setAttributeNode(idAttrib);
        }

        if (maxLen && maxLen != "" && maxLen > 0) {
            var maxLenAttrib = document.createAttribute("maxlength");
            maxLenAttrib.nodeValue = maxLen;
            newElem.setAttributeNode(maxLenAttrib);
        }

        if (tabIndex && tabIndex != "") {
            var tabIndexAttrib = document.createAttribute("tabindex");
            tabIndexAttrib.nodeValue = tabIndex;
            newElem.setAttributeNode(tabIndexAttrib);
        }

        if (sizeVal && sizeVal != "") {
            var sizeValAttrib = document.createAttribute("size");
            sizeValAttrib.nodeValue = sizeVal;
            newElem.setAttributeNode(sizeValAttrib);
        }

        var blurAttrib = document.createAttribute("onblur");
        blurAttrib.nodeValue = "switchToText(this,'" + defaultText + "');";
        newElem.setAttributeNode(blurAttrib);


        var par = elm.parentNode;
        par.replaceChild(newElem, elm);
        if (ie) {
            setTimeout("document.getElementById('" + idVal + "').focus();", 20);
        }
        else {
            newElem.focus();
        }
    }
}

var TAObserver = Class.create({
    init : function(elementId, maxChars, lettersLeft) {
        this.lettersLeft = lettersLeft;
        this.element = $(elementId);
        this.statusElement = $(elementId + '_status');
        this.maxChars = maxChars;
        this.element.observe("keydown", this.trigger.bind(this));
        this.element.observe("keyup", this.trigger.bind(this));
        this.element.observe("change", this.trigger.bind(this));
        this.trigger();
    },
    trigger : function(event) {
        if (this.element.value.length > this.maxChars) {
            this.element.value = this.element.value.substring(0, this.maxChars);
        }
        this.statusElement.innerHTML = (this.maxChars - this.element.value.length) + " " + this.lettersLeft;
        return true;
    }
});

function clearInput(obj, stdText) {
    if (obj.value == stdText) {
        obj.value = "";
    }
}

function restoreInput(obj, stdText) {
    if (obj.value == "") {
        obj.value = stdText;
    }
}

var ToolTip = Class.create({
    init: function(elementId, text) {
        this.element = $(elementId);
        this.layer = new Element('div', {style: 'position: absolute', 'class':'tooltip'});
        this.layer.innerHTML = text;
        this.layer.hide();
        this.offsets = this.getOffsets();
        this.layer.setStyle({top: this.offsets.y + 'px', left: this.offsets.x + 'px' });
        this.element.observe("mouseover", this.show.bind(this));
        this.element.observe("mouseout", this.hide.bind(this));
        document.observe("dom:loaded", this.addLayer.bind(this));
    },
    addLayer: function() {
        document.body.appendChild(this.layer);
    },
    show: function() {
        if (!this.layer.visible()) {
            this.layer.show();
        }
    },
    hide: function() {
        if (this.layer.visible()) {
            this.layer.hide();
        }
    },
    getOffsets: function() {
        obj = this.element;
        for (var x = 0, y = 0; obj != null; x += obj.offsetLeft,y += obj.offsetTop,obj = obj.offsetParent);
        return { x: (x + this.element.offsetWidth + 10), y: y }
    }
});

var ParticipantEditor = Class.create({
    initialize: function(form, profession, autocompleteUrl, addTitle, removeTitle) {
        this.form = $(form);
        this.profession = profession;
        this.parent = $((profession + 'Parent'));
        this.participants = [];
        this.autocompleteUrl = autocompleteUrl;
        this.addTitle = addTitle;
        this.removeTitle = removeTitle;

        if (this.form) {
            for (var i = 0; i < this.form.elements.length; i++) {
                var element = this.form.elements[i];
                if (element.name == this.profession) {
                    this.registerElement(this.getIndex(element));
                }
            }
        }
    },

    registerElement: function(index) {
        var element = $((this.profession + '[' + index + ']'));
        var buttonId = this.profession + 'Button[' + index + ']';
        var containerId = this.profession + 'Container[' + index + ']';
        var autocompleteId = this.profession + 'List[' + index + ']';
        var button = $(buttonId);
        var container = $(containerId);
        var autocompleteList = $(autocompleteId);
        var autocompleter = new Ajax.Autocompleter(
                element.id,
                autocompleteId,
                this.autocompleteUrl,
        { parameters:'type=' + this.profession, minChars:1, paramName:'value'});

        button.observe('click', this.click.bind(this));

        var participant = {
            index: index,
            button: button,
            element: element,
            container: container,
            autocompleteList: autocompleteList,
            autocompleter: autocompleter
        };

        this.participants.push(participant);
    },

    getIndex: function(element) {
        var strIdx = element.id && element.id.indexOf('[');
        if (strIdx != -1) {
            return parseInt(element.id.substring(strIdx + 1, element.id.length));
        }
        return -1;
    },

    getMaxIndex: function() {
        var result = -1;
        for (var i = 0; i < this.participants.length; i++) {
            if (this.participants[i].index > result) {
                result = this.participants[i].index;
            }
        }
        return result;
    },

    getNextIndex: function() {
        return (this.getMaxIndex() + 1);
    },

    click: function(event) {
        var button = event.element();
        var idx = this.getIndex(button);
        if (idx == this.getMaxIndex()) {
            this.add();
        }
        else {
            this.remove(idx);
        }
    },

    add: function() {
        var index = this.getNextIndex();
        for (var i = 0; i < this.participants.length; i++) {
            this.participants[i].button.value = 'X';
            this.participants[i].button.title = this.removeTitle;
        }
        this.createDom(index);
        this.registerElement(index);
    },

    remove: function(index) {
        var tmp = [];
        var count = 0;
        for (var i = 0; i < this.participants.length; i++) {
            if (this.participants[i].index == index) {
                this.parent.removeChild(this.participants[i].container);
            }
            else {
                var p = this.participants[i];
                p.index = count;
                p.element.id = this.profession + '[' + count + ']';
                p.button.id = this.profession + 'Button[' + count + ']';
                p.autocompleteList.id = this.profession + 'List[' + count + ']';
                p.container.id = this.profession + 'Container[' + count + ']';
                tmp.push(p);
                count++;
            }
        }
        this.participants = tmp;
    },


    createDom: function(index) {
        var elementId = this.profession + '[' + index + ']';
        var buttonId = this.profession + 'Button[' + index + ']';
        var containerId = this.profession + 'Container[' + index + ']';
        var autocompleteId = this.profession + 'List[' + index + ']';

        var element = new Element('input', { id: elementId, autocomplete: 'off', name: this.profession, type: 'text'});
        var container = new Element('div', {id: containerId, style: 'clear:both;'});
        var button = new Element('input', {id: buttonId, value: '+', 'class': 'button', type: 'button', title: this.addTitle});
        var acList = new Element('div', {id: autocompleteId, 'class': 'autocomplete'});

        container.appendChild(element);
        container.appendChild(button);
        container.appendChild(acList);
        this.parent.appendChild(container);
    }


});

function activateTab(e) {
    var element = Element.extend(e);
    var activeLi = e.up('li');
    var list = activeLi.up('ul');
    element.addClassName('active');
    for (var i = 0; i < list.childElements().length; i++) {
        var li = list.childElements()[i];
        if (li != activeLi) {
            li.down('a').removeClassName('active');
        }
    }
}
