var bcalendar = null;
var storage = new Object();

function init_override() {
    var cal = document.getElementById('ajcalendar');
    if (cal) {
        calendar();
    }
    initialize_yeartable();
}

function WeekCalendar(element_id, xml) {
    this.dayNames = new Array('Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag', 'Søndag');
    this.fields = new Array('timestamp', 'enabled', 'count', 'class', 'type', 'hour', 'minute');
    this.labels = new Array();
    this.config = new Array();
    this.configTrans = new Array();
    this.items = new Array();
    this.element = document.getElementById(element_id);
    this.container = document.createElement("table");
    this.outer = document.createElement('div');
    this.parse(xml);
    this.week = parseInt(this.getConfig("week"));
    this.year = parseInt(this.getConfig("year"));
    this.baselink = this.getConfig("baselink");
    this.outer.appendChild(this.container);
}

WeekCalendar.prototype.draw = function() {
    this.container.setAttribute("cellspacing", '1');
    this.container.setAttribute("class", "hours full");
    this.draw_top_row();
    this.draw_body();
    document.getElementById(this.element.id).innerHTML = this.outer.innerHTML;
}

WeekCalendar.prototype.find_column = function(node) {
    var column = 0;
    var tr = node.parentNode.parentNode;
    var tds = tr.getElementsByTagName('td')
    for (i=0; i<tds.length; i++) {
        if (tds[i].getElementsByTagName('a')[0] == node) column = tds.length == 8 ? i : i+1;
    }
    return column;
}

WeekCalendar.prototype.find_row = function(node, column) {
    var column = 0;
    var table = node.parentNode.parentNode.parentNode;
    var trs = table.getElementsByTagName('tr')
    for (i=0; i<trs.length; i++) {
        var tds = trs[i].getElementsByTagName('td');
        for (u=0; u<tds.length; u++) {
            if (tds[u].getElementsByTagName('a')[0] == node) row = i;
        }
    }
    return row;
}


WeekCalendar.prototype.raise = function(e) {
    var column = bcalendar.find_column(e);
    var row = bcalendar.find_row(e, column);
    // now highlight down the line
    // first, find out how many blocks should be highlighted
    var blocks = bcalendar.getConfig('duration_to_pick');
    var rows = blocks*2;
    var table = e.parentNode.parentNode.parentNode;
    var trs = table.getElementsByTagName('tr');
    for (i=0; i<trs.length; i++) {
        if (i>=row && i<row+rows) {
            // we're inside the scope, so highlight the cell at the column index
            var tds = trs[i].getElementsByTagName('td');
            var td = tds[tds.length == 8 ? column : column-1];
            // assign ID, store in object then highlight
            var id = 'bc'+Math.round(Math.random(100000,999999)*5246542654);
            td.setAttribute('id', id);
            var link = td.getElementsByTagName('a')[0];
            link.id = 'cap'+id;
            storage[link.id] = getStyle(link.id, 'backgroundColor');
            td.getElementsByTagName('a')[0].style.backgroundColor = '#f9ac17';
        }
    }
    return false;
}

WeekCalendar.prototype.lower = function(e) {
    // clear the storage object by resetting and removing backgroundColor definitions
    for (i in storage) {
        var element = document.getElementById(i);
        if (element) {
            document.getElementById(i).style.backgroundColor = storage[i];
            document.getElementById(i).removeAttribute('id');
        }
        delete(storage[i]);
    }
    return false;
}

WeekCalendar.prototype.draw_top_row = function() {
    var nextweek = this.getConfig('nextweek');
    var lastweek = this.getConfig('prevweek');
    var nextyear = this.getConfig('nextyear');
    var lastyear = this.getConfig('prevyear');

    var c = this.container;
    var thead = document.createElement("thead");
    var thead = c.appendChild(thead);
    var tr = document.createElement("tr");
    var tr = thead.appendChild(tr);
    tr.setAttribute("class", "browse");
    
    // previous link
    var td = document.createElement("td");
    var td = tr.appendChild(td);
    var prev = document.createElement("a");
    var prev = td.appendChild(prev);
    var img = document.createElement("img");
    var img = prev.appendChild(img);
    td.setAttribute("colspan", 2);
    td.setAttribute("style", "text-align: left");
    img.setAttribute("src", "/lib/icons/default/previous.png");
    img.setAttribute("class", "icon16");
    var text = document.createTextNode(lastweek+" "+lastyear);
    prev.appendChild(text);
    prev.setAttribute("href", "javascript:bigcalendar("+lastyear+","+lastweek+", 1, '"+encodeURIComponent(this.baselink)+"');");
    
    // current
    var td = document.createElement("td");
    var td = tr.appendChild(td);
    var label = document.createTextNode("Uge "+(this.week)+" "+this.year);
    td.appendChild(label);
    td.setAttribute("colspan", 4);
    
    // next link
    var td = document.createElement("td")
    var td = tr.appendChild(td);
    var next = document.createElement("a");
    var next = td.appendChild(next);
    td.setAttribute("colspan", 2);
    td.setAttribute("style", "text-align: right");
    var text = document.createTextNode(nextweek+" "+nextyear);
    next.appendChild(text);
    next.setAttribute("href", "javascript:bigcalendar("+nextyear+","+nextweek+",1,'"+encodeURIComponent(this.baselink)+"');");
    var img = document.createElement("img");
    var img = next.appendChild(img);
    img.setAttribute("src", "/lib/icons/default/next.png");
    img.setAttribute("class", "icon16");
    
    var tr = document.createElement("tr");
    var tr = thead.appendChild(tr);
    var td = document.createElement("td");
    var td = tr.appendChild(td);
    var limit = parseInt(this.getConfig("days"));
    td.innerHTML = '&nbsp;';
    for (i=0; i<limit; i++) {
        var td = document.createElement("td");
        var td = tr.appendChild(td);
        //td.setAttribute('style', 'border-bottom: 1px solid black;');
        var text = document.createTextNode(this.dayNames[i].substring(0,3));
        td.appendChild(text);
        var br = document.createElement("br");
        td.appendChild(br);
        var label = document.createTextNode(this.labels[i]);
        td.appendChild(label);
    }
}

WeekCalendar.prototype.get_item_from_timestamp = function(timestamp) {
    for (i in this.items) {
        if (this.items[i]["timestamp"] == timestamp) return this.items[i];
    }
    return false;
}

WeekCalendar.prototype.draw_body = function() {
    var c = this.container;
    var time = parseInt(this.getConfig("timestamp"));
    var intervals = parseInt(this.getConfig("intervals"));
    var endtime = time+parseInt(7*86400);
    var starthours = parseInt(this.getConfig("starthours"));
    var endhours = parseInt(this.getConfig("endhours"));
    var columns = new Array();
    var date = new Date(this.getConfig("date"));
    var runs = hour = minute = column = count= oclass = 0;
    var maxcount = parseInt(this.getConfig("maxcount"));
    var baselink = this.getConfig("baselink");
    
    for (i=0; i<this.items.length; i++) {
        var item = this.items[i];
        if (item) {
            hour = item[5];
            minute = item[6];
            time = item[0];
            count = parseInt(item[2]);
            oclass = item[3]
            
            var td = document.createElement("td");
            var link = document.createElement("a");
            td.appendChild(link);
            
            if (oclass != "off" && oclass != "p3") link.setAttribute("href", this.baselink+"date="+time);
            else if (oclass == "p5") link.setAttribute("href", this.baselink+"date="+time+"&price=exp");
            
            if (oclass == "p2") {
                var free = maxcount - count;
                var text = document.createTextNode(free);
                link.appendChild(text);
            }
            
            link.setAttribute("class", oclass);
            link.setAttribute("title", "Tiden begynder kl. "+hour+":"+minute);
            link.setAttribute('onmouseover', 'bcalendar.raise(this)');
            link.setAttribute('onmouseout', 'bcalendar.lower(this)');
            
            if (!columns[column]) columns[column] = new Array();
            columns[column].push(td);
            
            runs++;
            if (runs == intervals) {
                column++;
                runs = 0;
            }
        }
    }
    
    var rows = columns[0].length;
    var label_rendered = false;
    var day = r = 0;
    hour = starthours;
    
    for (r=0; r<rows; r++) {
        // one row each loop
        var tr = document.createElement("tr");
        var tr = c.appendChild(tr);
        tr.setAttribute("class", "hours");
        for (day=0; day<7; day++) {
            // one field each loop except day zero which has two (label and link)
            if (day == 0 && hour%1 == 0) {
                var td = document.createElement("td");
                var td = tr.appendChild(td);
                var text = document.createTextNode(hour);
                td.appendChild(text);
                td.setAttribute("class", "hours");
                td.setAttribute("rowspan", 2);
                td.setAttribute('style', 'font-size: 24px;');
            }
            
            if (columns[day]) {
                var td = columns[day].shift();
                if (td) td = tr.appendChild(td);
            } else {
                
            }
            
        }
        hour = hour+0.5;
    }


}

WeekCalendar.prototype.draw_bottom_row = function() {
    var c = this.container;
    var tr = document.createElement("tr");
    var tr = c.appendChild(tr);
    var td = document.createElement("td");
    var td = tr.appendChild(td);
    var text = document.createTextNode('bundrække');
    td.appendChild(text);
    td.setAttribute("colspan", this.days+1);
}

WeekCalendar.prototype.getConfig = function(item) {
    var key = null;
    for (i=0; i<this.configTrans.length; i++) {
        if (this.configTrans[i] == item) {
            key = i;
            break;
        }
    }
    if (key) return this.config[key];
    else return null;
}

WeekCalendar.prototype.parse = function(xml) {
    try { 
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML(xml);
    } catch(e) {
        try { 
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(xml,"text/xml");
        } catch(e) { return; }
    }
    
    var tags = xmlDoc.getElementsByTagName('option');
    var array = new Array();
    var value = label = null;
    for (i=0; i<tags.length; i++) {
        label = tags[i].getAttribute("name");
        if (tags[i].childNodes && tags[i].childNodes[0] && tags[i].childNodes[0].nodeValue) value = tags[i].childNodes[0].nodeValue;
        else value = tags[i].nodeValue;
        array[i] = value;
        this.configTrans.push(label);
    }
    this.config = array;
    
    var tags = xmlDoc.getElementsByTagName('label');
    var labels = new Array();
    for (i=0; i<tags.length; i++) {
        if (tags[i].childNodes[0].nodeValue) value = tags[i].childNodes[0].nodeValue;
        else value = tags[i].nodeValue
        labels[i] = value;
    }
    this.labels = labels;
    
    var tags = xmlDoc.getElementsByTagName('block');
    var items = this.items;
    
    for (i=0; i<tags.length; i++) {
        var array = new Array();
        for (f=0; f<this.fields.length; f++) {
            var value = tags[i].getElementsByTagName(this.fields[f])[0];
            if (value.childNodes[0]) value = value.childNodes[0].nodeValue;
            else value = value.nodeValue;
            array[f] = value;
        }
        items.push(array);
    }
    this.items = items;
}











































function quicksearch(query, target) {
    window.location.href += '&'+target+'='+query;
}

function show_payment(id) {
    for (i=0; i<=10; i++) {
        var element = document.getElementById('pay'+i);
        if (element) {
            if (id == i) {
                element.style.display = 'block';
            } else {
                element.style.display = 'none';
            }
        }
    }
}

function submit_product_form(finalized) {
    var form = document.getElementById('productform');
    var disable = document.createElement("input");
    
    disable.setAttribute("name", "disablepost");
    disable.setAttribute("type", "hidden");
    disable.setAttribute("value", "true");
    form.appendChild(disable);
    if (finalized) {
        var fin = document.createElement("input");
        fin.setAttribute("name", "finalized");
        fin.setAttribute("type", "hidden");
        fin.setAttribute("value", "true");
        form.appendChild(fin);
    }
    
    form.submit();
    var tags = document.getElementsByTagName('input');
    for (i=0; i<tags.length; i++) {
        tags[i].disabled = 'disabled';
    }
}

function submit_race_type_form() {
    var table = document.getElementById('racetypetable');
    var radios = table.getElementsByTagName('input');
    var found_checked_type = false;
    var found_checked_duration = null;
    for (r=0; r<radios.length; r++) {
        if (radios[r] && radios[r].type == "radio") {
            if (radios[r].checked == "checked" || radios[r].checked == true) {
                found_checked_type = true;
                var radios = radios[r].parentNode.parentNode.getElementsByTagName('input');
                if (radios.length > 1) {
                    for (r=0; r<radios.length; r++) {
                        //alert(radios[r].Name);
                        if (radios[r]) {
                            if (radios[r].name == 'duration' && (radios[r].checked == true || radios[r].checked == 'checked')) {
                                found_checked_duration = true;
                                //alert('found!');
                                break;
                            } else {
                                found_checked_duration = false;
                                //alert('not found');
                            }
                        }
                    }
                }
            }
        }
    }
    
    if (found_checked_type == true && (found_checked_duration == true || found_checked_duration == null)) document.getElementById('resform').submit();
    else alert('Du skal vælge en race type og eventuelt varighed');
    
    //alert(true);
}

function highlight(cur) {
    var table = document.getElementById('racetypetable');
    var all = table.getElementsByTagName('td');
    for (t in all) {
        if (all[t].id == cur && all[t].style) all[t].style.border = '1px solid silver';
        else if (all[t].style) all[t].style.border = '1px solid transparent';
    }
}


var blinkinstance = null;
function blink(object, color) {
    if (typeof object == "object") object = 'bsubmit';
    clearTimeout(blinkinstance);
    var element = window.document.getElementById(object);
    if (!element) return null;
    //var element = element.getElementsByTagName('img')[0];
    //element.id = 'ccd254244412';
    
    increment = 5;
    delay = 250;
    
    for (i=1; i<8; i++) {
        if (i%2) var opacity = 0.2;
        else var opacity = 1;
        setOpacity(element.id, opacity);
        while (opacity <= 1 && opacity >= 0.2) {
            var command = "setOpacity('"+element.id+"',"+opacity+")";
            blinkinstance = setTimeout(command, delay);
            delay = delay+increment;
            if (i%2) opacity = opacity+0.01;
            else opacity = opacity-0.01;
        }
        delay += 100;
    }
    //setTimeout('clearTimeout(blinkinstance)', delay);
}

function flash(text, iteration, direction, count) {
    if (typeof text == 'string') text = document.getElementById(text);
    if (!iteration) iteration = 0;
    if (!direction) direction = 0;
    if (!count) count = 1;
    if (count <= 275) {
        //text.style.border = '1px solid rgb('+iteration+',0,0)';
        text.style.color = 'rgb('+iteration+',0,0)';
        if (direction == 0 && iteration <= 255) {
            count++;
            iteration += 10;
            direction = 0;
            var com = 'flash('+text.id+', '+iteration+','+direction+','+(count)+')';
            setTimeout(com, 1);
        } else {
            count += 1;
            iteration -= 10;
            if (iteration < 0) direction = 0;
            else direction = 1;
            var com = 'flash('+text.id+', '+iteration+','+direction+','+(count)+')';
            setTimeout(com, 1);
        }
    }
}

