var xmlhttp
var model_id = -1; 

function findPos(obj) 
{
    var curleft = curtop = 0;
    if (obj.offsetParent) 
    {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) 
        {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}

function setCityListPosition()
{
    document.getElementById('list_container').style.left = findPos(document.newItemForm.queryText)[0]+"px";
    document.getElementById('list_container').style.top = (findPos(document.newItemForm.queryText)[1]+20)+"px";
}

function loadXMLDoc(url, functionCall)
{
    xmlhttp=null;    
    if (window.XMLHttpRequest)
    {   // code for all new browsers
        xmlhttp=new XMLHttpRequest();
    }  
    else if (window.ActiveXObject)
    {   // code for IE5 and IE6
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp!=null)
    {
        xmlhttp.onreadystatechange=functionCall;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
}

function state_Change()
{
    // if xmlhttp shows "loaded"
    if (xmlhttp.readyState==4)
    {
        // if "OK"
        if (xmlhttp.status==200)
        {
            var tekst = xmlhttp.responseText;
            var items = new Array();
            items = tekst.split(";");
            document.newItemForm.selObj.options.length = 0;
            if (document.newItemForm.queryText.value != "")
            {
                for (i = 0 ; i < (items.length)-1; i++)
                {
                    with (document.newItemForm.selObj)
                    {
                        id_name = items[i].split("|");
                        newItem = options.length;
                        options[newItem] = new Option(id_name[1]);
                        options[newItem].value = id_name[0];
                    }
                }
                document.newItemForm.selObj.style.display = 'inline';
            }
            else
            {
                with (document.newItemForm.selObj)
                {
                    document.newItemForm.selObj.options.length = 0;
                    document.newItemForm.selObj.style.display = 'none';
                }
                document.newItemForm.selObj.style.display = 'none';
            }
        }
        else
        {
            alert("Problem retrieving data:" + xmlhttp.statusText)
        }
    }
}

function setEntryTitles()
{
    var monthArray = new Array();
    monthArray['01'] = "januari";
    monthArray['02'] = "februari";
    monthArray['03'] = "maart";
    monthArray['04'] = "april";
    monthArray['05'] = "mei";
    monthArray['06'] = "juni";
    monthArray['07'] = "juli";
    monthArray['08'] = "augustus";
    monthArray['09'] = "september";
    monthArray['10'] = "oktober";
    monthArray['11'] = "november";
    monthArray['12'] = "december";

    // if xmlhttp shows "loaded"
    if (xmlhttp.readyState==4)
    {
        // if "OK"
        if (xmlhttp.status==200)
        {  
            var tekst = xmlhttp.responseText;
            var items = new Array();
            var items = tekst.split(";");
            var entryTable  = document.getElementById('entry_table');
            // verwijder allereerst de children van de entrytable zodat deze leeg is
            if (entryTable.childNodes)
            {
                while(entryTable.firstChild) 
                { 
                    entryTable.removeChild(entryTable.firstChild);
                }
            }

            // plaats en de entrytabel de nieuwe entries
            for (i = 0 ; i < (items.length)-1; i++)
            {
                cellValues = items[i].split("|");
                newTR = document.createElement('tr');
                newTD = document.createElement('td');
                newTD.style.paddingLeft = "10px";
                newLink = document.createElement('a');
                newLink.setAttribute('href', 'index.php?w_id='+cellValues[2]+'&s_id='+cellValues[3]+'&e_id='+cellValues[0]+'&date='+cellValues[4]+'&frontpage='+cellValues[5])
                newText = document.createTextNode(" • "+cellValues[1]);
                newLink.appendChild(newText);
                newTD.appendChild(newLink);
                newTR.appendChild(newTD);
                entryTable.appendChild(newTR);  
            }
            // nu moet de datum in de titelbalk nog worden aangepast
            var dateCell = document.getElementById('dateCell'); 
            while(dateCell.firstChild) 
            {
                dateCell.removeChild(dateCell.firstChild); 
            }

            dateParts = cellValues[4].split("_"); 
            if (cellValues[5] != 'true')
                dateCellText = document.createTextNode("Publicaties: "+monthArray[dateParts[1]]+" "+dateParts[0]);
            else 
                dateCellText = document.createTextNode("Laatste publicaties:");
            dateCell.appendChild(dateCellText);
        }
        else
        {
            alert("Problem retrieving data:" + xmlhttp.statusText)
        }
    }
}

function loadItemsFromDB(query, event)
{
    if (event.keyCode == 40)
    {
        checkFocus(event);
    }
    else
    {
        loadXMLDoc('functions/list_loader.php?query='+query, state_Change);
    }
}

function loadEntriesFromDB(log_id, s_id, date, frontpage, max)
{
    loadXMLDoc('functions/entry_loader.php?date='+date+'&log_id='+log_id+'&s_id='+s_id+'&frontpage='+frontpage+'&max='+max, setEntryTitles);
}

function doSel(value,text)
{
    document.newItemForm.queryText.value = text;
    document.newItemForm.nl_id.value = value;
    document.newItemForm.selectedValue.value = value;
    document.newItemForm.selObj.options.length = 0;
    document.newItemForm.selObj.style.display = 'none';
}

function hideList()
{
    document.newItemForm.queryText.value = document.newItemForm.selectedValue.value;
    document.newItemForm.selObj.options.length = 0;
    document.newItemForm.selObj.style.display = 'none';
}

function checkFocus()
{
    if (document.newItemForm.selObj.style.display != 'none')
    {
        document.newItemForm.selObj.focus();
    }
}

function checkSelection(value, text, event)
{
    if (event.keyCode == 13)
    {
        doSel(value, text);
    }
}

var rate = -1;  

function fillStars(starNumber)
{
    for (var i = 1; i <= starNumber; i++)
    {
        var star = document.getElementById("star_"+i);
        star.src = "images/star_blue.png";
    }  
}

function setMediaRate(_rate)
{
    rate = _rate;
}

function clearStars()
{
    for (var i = 1; i <= 5; i++)
    {
        var star = document.getElementById("star_"+i); 
        if (rate - (i*2) >= 0)
        {
            star.src = 'images/star_red.png';     
        }
        else if (rate - (i*2) <= 0 &&  rate - (i*2) >= -1)
        {
            star.src = 'images/star_red_grey.png'; 
        }
        else
        {
            star.src = 'images/star_grey.png';  
        }
    }  
}

function disableStars()
{
    for (var i = 1; i <= 5; i++)
    {
        var star = document.getElementById("star_"+i); 
        star.onmouseover  = null;
        star.onmouseout   = null;
        star.onclick      = null;
    } 
    var div = document.getElementById('allready_voted');
    div.style.display = 'block';
}

function updateMediaVote(hash, rate, ip)
{
    loadXMLDoc('functions/media_vote.php?hash='+hash+'&rate='+rate+'&ip='+ip, handleMediaVote);
}

function handleMediaVote()
{
    // if xmlhttp shows "loaded"
    if (xmlhttp.readyState==4)
    {
        // if "OK"
        if (xmlhttp.status==200)
        {
            var xmlDoc = xmlhttp.responseXML.documentElement;
            var rate = xmlDoc.getElementsByTagName("rate")[0].childNodes[0].nodeValue;
            setMediaRate(rate);
            clearStars(rate);
            disableStars();
        }
        else
        {
            alert("Problem retrieving data:" + xmlhttp.statusText)
        }
    }
}

function loadTypesForMake(a_url, make_id, a_model_id)
{
    model_id = a_model_id;
    document.getElementById('typeSelect').disabled = "disabled";
    url = a_url+make_id;
    loadXMLDoc(url, setMakeTypes);
}  

function setMakeTypes()
{
    if (xmlhttp.readyState==4)
    {   // 4 = "loaded"
        if (xmlhttp.status==200)
        {   // 200 = OK
            var xml     = xmlhttp.responseXML.documentElement;
            var models  = xml.getElementsByTagName('model'); 
            with (document.getElementById('typeSelect'))
            {
                options.length          = 0;
                options[0]              = new Option('selecteer...');
                options[0].value        = -1;
                for (i = 0 ; i < models.length; i++)
                {                
                    newItem                 = options.length; 
                    options[newItem]        = new Option(models[i].getElementsByTagName('description')[0].firstChild.nodeValue);
                    options[newItem].value  = models[i].getElementsByTagName('id')[0].firstChild.nodeValue;
                    if (options[newItem].value == model_id)
                    {
                        options[newItem].selected = true;
                    }
                }
                disabled = "";
            } 
        }
        else
        {
            alert("Problem retrieving XML data");
        }
    }
}

function setOrderByValue(a_order_by, a_direction)
{
    with (document.queryForm)
    { 
        if (order_by.value == a_order_by)
        {
            order_by_sort.value = a_direction;
        }
        order_by.value = a_order_by; 
        submit();
    }
}

function resetCompanyList()
{
    with (document.queryForm)
    { 
        company_id.selectedIndex = 0;
    }
}

function selectOccasion(a_auto_id)
{
    with (document.queryForm)
    {
        auto_id.value = a_auto_id;
        submit();
    }
}

function submitOccasionForm()
{
    with (document.queryForm)
    {
        if (year_from.value != "" && IsNumeric(year_from.value) == false)
        {
            year_from.focus();
            alert("U dient een geldig waarde in het veld 'bouwjaar van' in te voeren");
        }
        else if (year_until.value != "" && IsNumeric(year_until.value) == false)
        {
            year_until.focus();  
            alert("U dient een geldig waarde in het veld 'bouwjaar tot' in te voeren");
        }
        else if (IsNumeric(year_until.value) && IsNumeric(year_from.value) && parseInt(year_from.value) > parseInt(year_until.value) )
        {
            year_until.focus();
            alert("De waarde van 'bouwjaar tot' dient groter te zijn dan 'bouwjaar van'."); 
        }
        else if (price_from.value != "" && IsNumeric(price_from.value) == false)
        {
            price_from.focus();
            alert("U dient een geldig waarde in het veld 'prijs van' in te voeren");
        }
        else if (price_until.value != "" && IsNumeric(price_until.value) == false)
        {
            price_until.focus();  
            alert("U dient een geldig waarde in het veld 'prijs tot' in te voeren");
        }
        else if (IsNumeric(price_until.value) && IsNumeric(price_from.value) && parseInt(price_from.value) > parseInt(price_until.value) )
        {
            year_until.focus();
            alert("De waarde van 'prijs tot' dient groter te zijn dan 'prijs van'."); 
        }
        else if (company_id.value != -1)
        {
            makes_id.selectedIndex = 0;
            model_id.selectedIndex = 0;
            doors_id.selectedIndex = 0;
            fuel_id.selectedIndex  = 0;
            year_from.value   = "";
            year_until.value  = "";
            price_from.value  = "";
            price_until.value = "";
            submit();
        }
        else
        {
            submit();
        }
    }
}

function IsNumeric(sText)
{
    var ValidChars = "0123456789";
    var IsNumber=true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) 
    { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function raiseMediaViews(id) 
{
    var currentTime = new Date()
    var time = currentTime.getTime();   
    loadXMLDoc('functions/media_raise_views.php?id='+id+'&time='+time, mediaViewsRaised);
}

function mediaViewsRaised()
{
    // DO SOMETHING USEFULL
}
