window.addEvent('domready',function() {
    cwlive.load();
});

var cwlive = {
    maxNameLength : 80,
    pre : 'cwlive_',
    parse : function (data) {

        if (data.produktname.length > cwlive.maxNameLength)
            data.produktname = data.produktname.substr(0,cwlive.maxNameLength) + '...';

        $(cwlive.pre + 'produktname').innerHTML = data.produktname;
        $(cwlive.pre + 'bild').src = data.bild;
        $(cwlive.pre + 'uvp').innerHTML = cwlive.num(data.uvp) + ' &euro;';
        $(cwlive.pre + 'aktueller_preis').innerHTML = cwlive.num(data.aktueller_preis) + ' &euro;';

        cwlive.stop = data.stop;
        cwlive.countdown();

        setInterval( cwlive.countdown,1000);

        $(cwlive.pre + 'loading').setStyle('display','none');
        $(cwlive.pre + 'content').setStyle('display','block');
    },

    num : function (str) {
        str = String(str);
        if (str.indexOf('.') == -1)
            return str + ',00';
        if (str.split('.')[1].length == 1)
            return str.replace('.',',') + '0';
        return str.replace('.',',');
    },

    countdown : function () {
        var left = Math.floor(cwlive.stop - new Date().getTime()/1000);

        var hours = String(Math.floor(left / 3600));
        var minutes = String(Math.floor(left % 3600 / 60) + 1);
        var seconds = String(Math.floor(left % 3600 % 60));

        minutes = minutes.length < 2 ? '0' + minutes : minutes;
        seconds = seconds.length < 2 ? '0' + seconds : seconds;

    $(cwlive.pre + 'left').innerHTML = hours + ':' + minutes + ':' + seconds;
    },

    load : function () {
        var hn = 'http://' + window.location.hostname + '/fileadmin/scripts/cwlive/cwlive.php';
		if (window.location.hostname == 'devel09') hn = 'http://' + window.location.hostname + '/cw_hubs/fileadmin/scripts/cwlive/cwlive.php';
        if (window.location.hostname == 'www.computerwissen.de') hn = 'http://' + window.location.hostname + '/cms/fileadmin/scripts/cwlive/cwlive.php';
        new Request.JSON( {
            url : hn,
            method : 'post',
            onComplete: cwlive.parse
        } ).send();
    }
};