/* PNlib */

/*jslint white: true, browser: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, newcap: true, immed: true */
/*global $, window, URL: true */
/*members addClass, apply, attr, bind, call, change, click, concat, 
    disable, each, enable, fn, hasOwnProperty, hide, host, html, join, 
    length, match, onFinish, open, parse, path, port, post, preload, 
    prototype, ready, reduce, regexp, removeClass, replace, reverse, scheme, 
    serialize, show, slice, split, text, url, val
*/

function format_float(val) {
    val = parseFloat(val);

    if (isNaN(val)) {
        return '';
    }

    return val;
}

// partial(f, *args)
function partial(f) {
    var args1 = Array.prototype.slice.call(arguments, 1);

    return function () {
        var args2 = Array.prototype.slice.call(arguments);
        return f.apply(this, args1.concat(args2));
    };
}

// reduce(f, initial)
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/reduce
if (!Array.prototype.reduce)
{
    Array.prototype.reduce = function (fun /*, initial*/)
    {
        var len = (this.length >>> 0);
        if (typeof fun !== "function") {
            throw new TypeError();
        }

        // no value to return if no initial value and an empty array
        if (len === 0 && arguments.length === 1) {
            throw new TypeError();
        }

        var rv;
        var i = 0;
        if (arguments.length >= 2) {
            rv = arguments[1];
        } else {
            do {
                if (i in this) {
                    rv = this[i];
                    i += 1;
                    break;
                }

                // if array contains no values, no initial value to return
                i += 1;
                if (i >= len) {
                    throw new TypeError();
                }
            } while (true);
        }

        for (; i < len; i += 1) {
            if (i in this) {
                rv = fun.call(null, rv, this[i], i, this);
            }
        }

        return rv;
    };
}

function get_price(element) {
    var selector = "label[for=" + element.attr("id") + "] > strong > span";
    return $(selector).text();
}

function adjust_price(element, amount) {
    var new_text = element.text().replace(",", ".") - amount;
    element.text(format_float(new_text));
}

String.prototype.reverse = function () {
    var splitext, revertext, reversed;
    splitext = this.split("");
    revertext = splitext.reverse();
    reversed = revertext.join("");
    return reversed;
};

$.fn.enable = function () {
    return $(this).attr("disabled", false);
};
$.fn.disable = function () {
    return $(this).attr("disabled", true);
};

URL = function () {};

URL.parse = function (url) {
    var result = this.url.match(this.regexp);
    this.url = url;
    this.scheme = result[1];
    this.host = result[2];
    this.port = result[3];
    this.path = result[4];
    return this;
};

URL.prototype.parse = URL.parse;
URL.prototype.regexp = /(https?:\/\/)([a-zA-Z0-9_\-\.]+)(:[0-9]+)?\/?(.*)?/;

function felder() {
    $(document).ready(function () {
        $("#previewbutton").hide();

        var defaults = {};

        $(".feld input:text").each(function () {
            var input = $(this);
            defaults[input.attr("id")] = input.val();

            function update_element() {
                var feldid = input.attr("id"); 
                var value = input.val();

                input.removeClass("error");

                if (defaults[feldid] !== value) {
                    input.removeClass("default");
                    $("span." + feldid).each(function () { 
                        $(this).removeClass("default"); 
                    });
                } else {
                    input.addClass("default"); 
                    $("span." + feldid).each(function () { 
                        $(this).addClass("default"); 
                    });
                }

                $("span." + feldid).each(function () { 
                    $(this).text(value); 
                });
            }

            input.bind("keyup", update_element);
        });
    });
}

function update_total() {
    $(document).ready(function () {

        function update_item(random_key) {
            return function () {
                var url;
                url = "/customize/" + random_key + "/update_basket/";
                $.post(url, $("form[name=basket]").serialize(),
                    function (data) {
                        var new_value;
                        for (var css_id in data) {
                            if (data.hasOwnProperty(css_id)) {
                                new_value = data[css_id];
                                $("span." + css_id).html(new_value || "");
                            }
                        }
                    }, "json");
            };
        }

        $("div.cust").each(function () {
            var div_id, random_key, radio, input, updater;

            div_id = $(this).attr('id');
            random_key = div_id.split('_')[1];

            updater = update_item(random_key);

            radio = "div#" + div_id + " input[type='radio']";
            input = "div#" + div_id + " input.n";

            $(radio).bind("click", updater);
            $(input).bind("keyup", updater);
        });
    });
}

function auto_popups() {
    $(document).ready(function () {
        $("a[target=popup]").click(function () {
            var features = "location=0,statusbar=0,menubar=0,width=600,height=600,top=50,left=100";
            var target = $(this).attr("target");
            var parts = $(this).attr("href").split('#');
            var fragment = parts[1] ? '#' + parts[1] : "";
            var href = parts[0] + "-popup" + fragment;
            window.open(href, target, features);
            return false;
        });
    });
}

function pictureSelector(gender) {
    $(document).ready(function () {
        var width, update_image;

        width = $("#thumb").attr('width');

        $("#vorschau input").hide();
        /* TODO
         * Cache filenames in an object, using
         * the values of the select boxes as keys
         **/
        update_image = function () {
            $("#loading").show();
            $.post('?image=' + width,
                $("form").serialize(),
                function (filename) {
                    $.preload([ filename ], {
                        onFinish: function (data) {
                            $("#thumb").attr("src", filename);
                            $("#loading").hide();
                        }
                    });
                }
            );
        };
        $("form select").change(update_image);

        /*
         * Wenn die Seite mit strg-r neu geladen wird
         * dann wird das Bild wieder auf das Standard-
         * Bild zurückgesetzt. Hier nochmal das korrekte
         * Bild für die ausgewählten Werte setzen.
         **/
        update_image();
    });
}


/* Tabs */

function activate_tab() {
    var name = $(this).attr("href").replace(/#/, "");
    $('#tabs > li').each(function () {
        $(this).removeClass("active");
    });
    $("#link_" + name).addClass("active");
    $('#tabcontents > li').hide();
    $("#" + name).show();
    return false;
}

function setup_tabs() {
    $('#tabs, #tabcontents').each(function () {
        $(this).removeClass("active");
        $(this).addClass("tab");
    });
    $('.toplink').hide();
    $("#tabs a").click(activate_tab);
    $("#tabs a").slice(0, 1).each(activate_tab);
}
