/* 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 url_join(url, querystring) {
    if (url.indexOf("?") > -1) {
        return url + "&" + querystring;
    } else {
        return url + "?" + querystring;
    }
}

function format_float(e) {
    if (e === 0)
      return "0,00";

    e = String(Math.round(100*e));
    l = e.length;
    e = e.substr(0, l-2) + "," + e.substr(l-2, l);
    ++l;
    if (l >= 7)
        e = e.substr(0, l-6) + "." + e.substr(l-6, l)
    return e
}

function to_float(s) {
    return parseFloat(s.replace(',','.'));
}

// 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;
    var format_float = function(val) {
        val = parseFloat(val);

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

        return val;
    }
    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();

        $("input.field").each(function () {
            var input = $(this);

            function update_element() {
                var feldid = input.attr("id");
                var value = input.val();
                var default_ = input.attr('data-default');

                input.removeClass("error");

                if (value !== default_) {
                    $("span."+feldid).add(input).removeClass("default");
                } else {
                    $("span."+feldid).add(input).addClass("default");
                }

                $("span." + feldid).text(value);
            }

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

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

        function update_item(random_key) {
            return function () {
                var 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 () {
        var auto_popup = "";
        var elements;
        if (!arguments[1]) {
            elements = $("a[target=popup]");
        } else {
            elements = arguments[1];
        }
        elements.not("a[src^='http']").click(function() {
            var features = "location=0,statusbar=0,menubar=0,width=600,height=600,top=50,left=100";
            var target = $(this).attr("target");
            var split_point = $(this).attr("href").search(/\/\?/);
            var href = "";
            if ( split_point == -1 ){
                split_point = $(this).attr("href").search(/\?/);
                if ( split_point == -1 ){
                    split_point = $(this).attr("href").search(/#/);
                    if ( split_point == -1 ){
                        href = $(this).attr("href") + "-popup";
                    }
                }
            }

            if ( href == '' ){
                href = $(this).attr("href").slice(0,split_point) + "-popup" + $(this).attr("href").slice(split_point);
            }
            //var parts = $(this).attr("href").split('#');
            //var fragment = parts[1] ? '#' + parts[1] : "";
            //var href = parts[0] + "-popup" + fragment;
            if (auto_popup) {
                /* Wenn bereits ein Popup offen ist, dann zuerst
                 * zu machen, damit das Popup wieder im Vordergrund
                 * erscheint. */
                auto_popup.close();
            }
            auto_popup = 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();
    });
}


function register_submit_validator(selector, validator, data, message) {
    $(selector).click(function() {
        if (!validator(data)) {
          return confirm(message);
        }
    });
}


/* Globales Twirly-Handling: Einfach CSS definieren, um bestimmte Elemente
 * unterhalb von body.please_wait zu verstecken/anzuzeigen, und dann diese
 * Funktionen aufrufen. */

function please_wait_start() {
    $("body").addClass('please_wait');
}

function please_wait_stop() {
    $("body").removeClass('please_wait');
}


/* 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);
}

function add_step_numbers(elems) {
  /* Text der übergebenen Elemente durchnummerieren. Beispiel:
     >>> add_step_numbers($("label[for=name], label[for=color]"))
   */
  for (var i = 0; i < elems.length; i+=1) {
      var e = $(elems[i]);
      e.text((i+1)+". "+e.text());
  }
}

/**
 * Count down timer to call a function at every full interval.
 *
 * @param seconds           Time in seconds to count down from.
 * @param interval          The time span between two callback calls.
 * @param tick_callback     Call this function at each FULL multiple of intenval
 *                          (that is, each time the remaining seconds are divisible
 *                          by interval), passing the remaining seconds as its
 *                          first argument.
 */
function countdown_timer(seconds, interval, tick_callback) {
    seconds_left = seconds;

    function step_timer() {
        var next_timeout = (seconds_left % interval) || interval;
        seconds_left -= next_timeout;
        setTimeout(tick_wrapper, next_timeout*1000);
    }

    function tick_wrapper() {
        // seconds_left will be changed by step_timer, but we want to pass
        // the current value to tick_callback
        var left = seconds_left;

        // Execution order is important. Otherwise, tick_callback might
        // block synchronously and delay the next step.
        if (seconds_left > 0) {
            step_timer();
        }
        tick_callback(left);
    }

    step_timer();
}
/*
 * Geklaut von
 * http://unixpapa.com/js/dyna.html
 * http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file/950146#950146
 */
function load_script(url, callback) {
    // adding the script tag to the head
   var body = document.getElementsByTagName('body')[0];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = url;

   // then bind the event to the callback function
   // there are several events for cross browser compatibility
   script.onreadystatechange = callback;
   script.onload = callback

   // fire the loading
   body.appendChild(script);
}

