/*   _________      ___                          ___     ___    
 *   \_   ___ \     \  |                         \  |   / _ \   
 *   /   /   \/ ____ | |__ _____  _____    ______|  |_ / /_\ \  
 *  /    \     /  _ \| __ \\__  \ \__  \  /  ___\   __/       \ 
 *  \     \___(  |_| | \_\ \/ __ \_/ __ \_\___ \ |  |/    |    \
 *   \______  /\____/|___  (____  (____  /____  ||__|\____|__  /
 *          \/           \/     \/     \/     \/             \/ 
 *              | ' |)    |? /\ ¨|¨ |-| [- |?    |} [-          
 *             _\¨ |< /\ ¨|¨ [- |} () /\ |? |) | |\| (¬         
 */

// Popup //////////////////////////////////////////////////////////////////////////////////////////

/* 
 * function opens the url specified with the parameter url
 * in a new window with, if specified, width x and height y.
 */
function openPopup(url,x,y) {
    if (!x) x = 270;
    if (!y) y = 400;
    var pop = window.open(url,"popup","dependent=yes,resizable=yes,scrollbars=yes,width="+x+",height="+y+",left=50,top=50");
    pop.focus();
}

// Contact ////////////////////////////////////////////////////////////////////////////////////////

/* 
 * function to avoid robots.
 */
function checkContact(form){
    form.token.value = Math.floor(Math.random()*1001) * (Math.pow(2, 31) - 1);
    form.submit();
}

// Sort ///////////////////////////////////////////////////////////////////////////////////////////

/* 
 * function sorts the rows of a table
 */
function sortTable(tableId, col, sortfunc, reverse) {
    if (!sortfunc) sortfunc = sortRowsByStr;
    if (!reverse) reverse = false;
    var tableRows = new Array();
    var table = document.getElementById(tableId);
    for (var i = 1; i < table.rows.length; i++) tableRows[i - 1] = table.rows[i];	// copy table rows to row array
    changeColums(tableRows, col, 0);	// set the column to sort at first position
    handleIndex(tableRows, true);		// append index to keep order of equal items, needed by mozilla
    tableRows.sort(sortfunc);			// call of array sort to sort by items in first table column
    handleIndex(tableRows, false);		// remove index to keep order of equal items, needed by mozilla
    changeColums(tableRows, col, 0);	// set the column sorted by back to original position
    if (reverse) tableRows.reverse();	// reverse the hole table if desired so
    for (var i = 0; i < tableRows.length; i++) table.tBodies[0].appendChild(tableRows[i]);	// copy row array to table rows
}

/* 
 * function changes colums of a table by switching them
 */
function changeColums(rows, cola, colb) {
    if (cola!=colb) {
        for (var i in rows) {
            var tmp = rows[i].cells[cola].innerHTML;
            rows[i].cells[cola].innerHTML = rows[i].cells[colb].innerHTML;
            rows[i].cells[colb].innerHTML = tmp;
        }
    }
}

/* 
 * function appends or removes index column.
 * needed because mozillas array sort function
 * doesnt keep existing order of equal items.
 */
function handleIndex(rows, append) {
    for (var i in rows) {
        if (append) {
            var td = document.createElement("td");
            var text = document.createTextNode(i);
            td.appendChild(text);
            rows[i].appendChild(td);
        }
        else {
            rows[i].deleteCell(rows[i].cells.length-1);
        }
    }
}

/* 
 * function sorts the rows numerically
 * accepts int and float, metric and american
 */
function sortRowsByNum(rowa, rowb) {
    var as = rowa.cells[0].innerHTML.split("'");	// if feets split in feets and inches
    var bs = rowb.cells[0].innerHTML.split("'");	// if feets split in feets and inches
    a = parseFloat(as[0]);							// parse default or feets
    b = parseFloat(bs[0]);							// parse default or feets
    if (as.length>1 && bs.length>1 && a==b) {		// if feets and feets are same
        a = parseFloat(as[1].replace("\"",""));		// parse inches
        b = parseFloat(bs[1].replace("\"",""));		// parse inches
    }
    if (a == b) return sortRowsByIndex(rowa, rowb);	// needed by mozilla
    return a-b;
}

/* 
 * function sorts the rows alphabetically
 */
function sortRowsByStr(rowa, rowb) {
    var a = rowa.cells[0].innerHTML;
    var b = rowb.cells[0].innerHTML;
    if (a == b) return sortRowsByIndex(rowa, rowb);	// needed by mozilla
    return a.localeCompare(b);
}

/* 
 * function sorts the rows alphabetically 
 * ignoring all html tags
 */
function sortRowsByHtm(rowa, rowb) {
    var a = rowa.cells[0].innerHTML.replace(/<(.|\n)+?>/ig, "");
    var b = rowb.cells[0].innerHTML.replace(/<(.|\n)+?>/ig, "");
    if (a == b) return sortRowsByIndex(rowa, rowb);	// needed by mozilla
    return a.localeCompare(b);
}

/* 
 * function sorts the rows by date
 */
function sortRowsByDat(rowa, rowb) {
    var exp = /(\d+)\.(\d+)\.(\d+)/;
    exp.exec(rowa.cells[0].innerHTML);
    var a = new Date(RegExp.$3, RegExp.$2-1, RegExp.$1);
    exp.exec(rowb.cells[0].innerHTML);
    var b = new Date(RegExp.$3, RegExp.$2-1, RegExp.$1);
    if (a == b) return sortRowsByIndex(rowa, rowb);	// needed by mozilla
    return b-a;
}

/* 
 * function sorts by previous ordering
 * needed because mozillas array sort function
 * doesnt keep existing order of equal items.
 */
function sortRowsByIndex(rowa, rowb) {
    var a = rowa.cells[rowa.cells.length-1].innerHTML;
    var b = rowb.cells[rowb.cells.length-1].innerHTML;
    return a-b;
}

// Calc ///////////////////////////////////////////////////////////////////////////////////////////

/* 
 * function calculates skateboard riding radius
 * out of pivot angle, lean and wheel base.
 */
function calculateRadius(form) {
    var steer = form.lean.value * form.pivot.value / 45;
    form.steer.value = Math.round(steer * 100) / 100;
    form.radius.value = Math.round(form.base.value / (2 * Math.sin(steer * Math.PI / 180)) * 100) / 100;
}

/* 
 * function converts cm to inch.
 */
function cm2inch(form) {
    form.inch.value = Math.round(form.cm.value * 0.394 * 100) / 100;
}

/* 
 * function converts inch to cm.
 */
function inch2cm(form) {
    form.cm.value = Math.round(form.inch.value * 2.54 * 100) / 100;
}

// Fun ////////////////////////////////////////////////////////////////////////////////////////////

/* 
 * function shakes the window for the amount specified with 
 * the parameter n.
 */
function shake(n) {
    if (!n) n = 10;
    if (self.moveBy) {
        for (i = 10; i > 0; i--) {
            for (j = n; j > 0; j--) {
                self.moveBy(0,i);
                self.moveBy(i,0);
                self.moveBy(0,-i);
                self.moveBy(-i,0);
            }
        }
    }
}

/* 
 * function stirs the window for the amount specified with 
 * the parameter n.
 */
function stir(n) {
    if (!n) n = 10;
    var x = 0;
    var y = 0;
    if (self.moveBy) {
        while (n > 0) {
            var r = -1.00;
            for (i = 0; i < 10; i++) {
                x = Math.floor(Math.cos((r*Math.PI)/2)*2);
                y = Math.floor(r*2);
                self.moveBy(x,y);
                r = r+0.1;
            }
            r = -1.00;
            for (i = 0; i < 10; i++) {
                x = Math.floor(Math.cos((r*Math.PI)/2)*2);
                y = Math.floor(r*2);
                self.moveBy(-x,-y);
                r = r+0.1;
            }
            n--;
        }
    }
}

/* 
 * function changes the color and background color
 * of an element specified with the parameter id.
 */
function changeColor(id, colorDez, rise, fall, change) {
    var hexChars = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
    var colorHex = "";
    var colorCompHex = "";
    var step = 1;
    if (!colorDez) colorDez = 0;
    if (!rise) rise = 1;
    if (!fall) fall = 2;
    if (!change) change = step;
    colorDez+=change;
    if (colorDez>=255){
        colorDez = 255;
        change = -step;
        fall>=3 ? fall = 1 : fall++;
    }
    else if (colorDez<=0) {
        colorDez = 0;
        change = step;
        rise>=3 ? rise = 1 : rise++;
    }
    colorHex = hexChars[Math.floor(colorDez/16)] + hexChars[colorDez%16];
    colorCompHex = hexChars[Math.floor((255-colorDez)/16)] + hexChars[(255-colorDez)%16];
    if (rise==1 && fall==2) { //6
        colorHex     = "#"+colorHex    +"00"+"FF";
        colorCompHex = "#"+colorCompHex+"FF"+"00";
    }
    if (rise==2 && fall==1) { //3
        colorHex     = "#"+colorHex    +"FF"+"00";
        colorCompHex = "#"+colorCompHex+"00"+"FF";
    }
    if (rise==1 && fall==3) { //1
        colorHex     = "#"+"FF"+"00"+colorHex;
        colorCompHex = "#"+"00"+"FF"+colorCompHex;
    }
    if (rise==3 && fall==1) { //4
        colorHex     = "#"+"00"+"FF"+colorHex;
        colorCompHex = "#"+"FF"+"00"+colorCompHex;
    }
    if (rise==2 && fall==3) { //2
        colorHex     = "#"+"FF"+colorHex    +"00";
        colorCompHex = "#"+"00"+colorCompHex+"FF";
    }
    if (rise==3 && fall==2) { //5
        colorHex     = "#"+"00"+colorHex    +"FF";
        colorCompHex = "#"+"FF"+colorCompHex+"00";
    }
    document.getElementById(id).style.backgroundImage = "none";
    document.getElementById(id).style.backgroundColor = colorHex;
    document.getElementById(id).style.color = colorCompHex;
    setTimeout("changeColor(\""+id+"\", "+colorDez+", "+rise+", "+fall+", "+change+")",10);
}

// Ajax ///////////////////////////////////////////////////////////////////////////////////////////

/* 
 * Gets the browser specific XmlHttpRequest Object.
 *
 * void open(DOMString method, DOMString url, [boolean async, DOMString user, DOMString password])
 * void send([DOMString data | Document data])
 * void abort()
 * void setRequestHeader(DOMString header, DOMString value)
 * DOMString getAllResponseHeaders() - Returns all http headers
 * DOMString getResponseHeader(DOMString header) - For "Content-Type" this is something like "Content-Type: text/plain; charset=utf-8"
 * EventListener onreadystatechange
 * short readyState - When readyState changes value a readystatechange event is to be dispatched on the XMLHttpRequest object.
 *   0 Uninitialized - The initial value.
 *   1 Open - The open() method has been successfully called.
 *   2 Sent - The user agent successfully acknowledged the request.
 *   3 Receiving - Immediately before receiving the message body (if any). All HTTP headers have been received.
 *   4 Loaded 
 * DOMString responseText - The response text.
 * Document responseXML - The response doc.
 * DOMString statusText - Represents the HTTP status text.
 * short status - Represents the HTTP status code (200 means ok).
 */
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}

/* 
 * Our XmlHttpRequest object to get Asynchronous JavaScript and XML.
 */
var ajax = getXmlHttpRequestObject();

/* 
 * Starts the AJAX request.
 * Called from onkeyup on the keyword input field.
 */
function imgSearch() {
    if (ajax.readyState == 1 || ajax.readyState == 2 || ajax.readyState == 3 || ajax.readyState == 4) { // onkeyup while waiting for response
        ajax.abort();                                                           // abort request with old keyword
        setTimeout("imgSearch()", 10);                                          // start request with new keyword
    }
    else if (ajax.readyState == 0) {                                            // normal case, ajax is ready
        var keyword = escape(document.getElementById('keyword').value);
        ajax.onreadystatechange = imgSearchResponse;
        ajax.open("GET", '/includes/ajax_imgsearch.php?keyword=' + keyword, true);
        ajax.send(null);
    }
}

/* 
 * Response of the AJAX request.
 * Called when the AJAX response is returned.
 */
function imgSearchResponse() {
    if (ajax.readyState == 4) { // response is loaded
        document.getElementById('response').innerHTML = ajax.responseText;
    }
}

/* 
 * Starts the AJAX request.
 * Called from onclick on the image thumb.
 */
function imgPrevNext(src) {
    if (ajax.readyState == 1 || ajax.readyState == 2 || ajax.readyState == 3 || ajax.readyState == 4) { // onkeyup while waiting for response
        ajax.abort();                                                           // abort request with old keyword
        setTimeout("imgPrevNext('" + src + "')", 10);                           // start request with new keyword
    }
    else if (ajax.readyState == 0) {                                            // normal case, ajax is ready
        ajax.onreadystatechange = imgPrevNextResponse;
        ajax.open("GET", '/includes/ajax_imgprevnext.php?src=' + src, true);
        ajax.send(null);
    }
}

/* 
 * Response of the AJAX request.
 * Called when the AJAX response is returned.
 */
function imgPrevNextResponse() {
    if (ajax.readyState == 4) { // response is loaded
        eval(ajax.responseText);
        document.getElementById('prev').onclick = function() { eval(prevnext.prev); return false; };
        document.getElementById('next').onclick = function() { eval(prevnext.next); return false; };
    }
}

/* 
 * Starts the AJAX request.
 * Called from onclick on the show/hide link of the right box.
 */
function session(key, value) {
    if (ajax.readyState == 4 || ajax.readyState == 0) {
        ajax.open("GET", '/includes/ajax_session.php?key=' + escape(key) + '&value=' + escape(value), true);
        ajax.send(null);
    }
}

// Dhtml //////////////////////////////////////////////////////////////////////////////////////////

function displayFromTo(fromId, toId, show) {
    for (var i=fromId; i<=toId; i++) {
        display(i, show);
    }
}

function display(id, show) {
    if (show) document.getElementById(id).style.display = '';
    else document.getElementById(id).style.display = 'none';
}

function setImage(id, path) {
    document.getElementById(id).src = path;
    document.getElementById(id).alt = path.replace(/\/img.*\/(.*)\.jpg/, '$1'); // get image name without dir and ending
    imgPrevNext(path);
}

function setPosition(id) {
    //var fromTop = (document.all) ? document.documentElement.scrollTop : window.pageYOffset;
    //if (document.getElementById(id).style.position != 'fixed') {
        //document.getElementById(id).style.top = fromTop +'px';
    //}
    var height = (document.all) ? document.documentElement.clientHeight : window.innerHeight;
    document.getElementById(id).style.height = height +'px';
    if (document.all) {
        document.getElementById(id).style.filter = 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000,endColorstr=#99000000);';
    }
    else {
        document.getElementById(id).style.background = 'rgba(0, 0, 0, 0.6)';
    }
}

