var PageView = function(target, filesindir, numimages, callback) {

    this.callback = callback;

    this.activated = false;

    this.dontMove = false;

    this.target = target;

    this.target$ = $(target);

    this.rail$ = $(".pageview-group", this.target$);

    this.rail$.empty();

    this.group = $(".pageview-group", this.target$).get(0);

    this.filesindir = filesindir;


    this.fadeInOut$ = $(".fade-out");

    this.fadeInOutIsVisible = true;

    this.mouseHasNotMovedCounter = 0;

    this.numimages = numimages;

    this.imageratios = {};

    this.WAITING = 0;

    this.ATTACHED = 1;

    this.DETACHING = 2;

    this.state = this.WAITING;

    this.now = new Date().getTime();


}

PageView.prototype = {

    elapsed : function() {
        return new Date().getTime()-this.now;
    },

    sendEvent : function(dir, up) { /* Create a new Event instance */

        var evt = "bookPageChanged";

        var nodes = this.group.childNodes;

        var options = { dir:dir, up:up, left: nodes[0], view: nodes[1], right: nodes[2] };

        $(this).trigger(evt, options);

    },

    doIphoneStuff : function() {

        debug("IPAD "+this.isIPhoneIPad());

        if (!this.isIPhoneIPad()) {
            return false;
        }

            $(".pageview-wrapper .arrows").remove();

//        $(document).bind("touchmove", function() {
//            debug("newsfade in touchmove ");
//        })

//        $(document).bind("touchstart", function() {
//            debug("newsfade in touchstart ");
//            if (event.touches[0].pageY<150) {
//                newsFadeIn();
//            }
//        })

            if (this.numimages > 1) {

                this.group.style.webkitTransitionDuration = 0;

                this.registerIPhoneIPadEvents();

            }

        return true;

    },

    doNotIphoneStuff : function() {

        var self = this;

        debug("not iphone");

        $(window).bind("mousemove", function(event) {
            self.newsFadeIn(event.pageY);
        })

        $(".left", this.target).click(function() {
            self.slideRight();
            return false;
        })

        $(".right", this.target).click(function() {
            self.slideLeft();
            return false;
        })

        $(window).bind("resize", function() {
            self.resize();
        })

    },

    init : function() {

        var self = this;


        window.setInterval(function() {

            if (!self.fadeInOutIsVisible) {
                return;
            }

            if (self.mouseHasNotMovedCounter > 3) {
                self.fadeInOutIsVisible = false;
                self.fadeInOut$.fadeOut(500);
            } else {
                self.mouseHasNotMovedCounter++;
            }

        }, 500);


        /* Initialization phase */



        if (!this.doIphoneStuff()) {

            this.doNotIphoneStuff();

        }


        this.sendEvent();





        $(".preloader", self.target$).css("display", "block");

        this.preloadImages();



    },

    preloadImages : function() {

        var total = 0;

        var stepsize = 100 / this.numimages;

        var self = this;

        var onload = function(x) {

            total++;

            $(".preloader span", self.target$).text(Math.floor(stepsize * total));

            // save imageratio of pre-loaded im age
            self.imageratios[this] = (this.width / this.height);


            if (total == self.numimages) {

                // we have finished pre-loading all images

                window.setTimeout(function() {
                    self.resize();
                }, 1);
            }

        };

        for (var i = 0; i < this.filesindir.length; i++) {

            var bgim = new Image();

            var im$ = $("<img>");

            var div$ = $("<div>");

            div$.append(im$);

            im$.css("display", "none");

            im$.attr("src", this.filesindir[i]);

            this.rail$.append(div$);

            if (this.isIPhoneIPad()) {

                im$.css("-webkit-transform", "translate3d(0, 0, 0)");

                div$.css("-webkit-transform", "translate3d(0, 0, 0)");

            }

            bgim.onload = onload;

            bgim.src = im$.attr("src");

        }

    },

    isIPhoneIPad : function() {
        return navigator.userAgent.match(/(ipad|iphone)/i);
    },


    clear : function() {

        this.rail$.empty();

    },

    resize : function() {

        this.items$ = $(".pageview-group div", this.target$);

        this.w$ = $(window);

        this.ww = this.w$.width();

        this.wh = this.w$.height();

        this.winr = this.ww / this.wh;

        this.rail$.width(this.numimages * this.ww);

        this.rail$.height(this.wh);

        this.items$.css("width", this.ww + "px");

        this.items$.css("height", this.wh + "px");

        if (this.numimages > 1) {
            this.rail$.css("left", "-" + ((1 * this.ww)) + "px");
        }

//    this.activate();

        this.resizeImages();

//            $("img:nth-child(2)", this.items$).fadeIn(function() {
//                $("img", this.items$).css("display", "block");
//            })


    },

    newsFadeIn : function(y) {


        var self = this;

        self.mouseHasNotMovedCounter = 0;

        if (self.fadeInOutIsVisible) {
            return;
        }

        if (y) {

            if (y > 150) {
                return;
            }

        }

        debug("news fades in");

        self.fadeInOutIsVisible = true;

        self.fadeInOut$.fadeIn(500, function() {

        });

    },

    activate : function() {

        var self = this;

        if (!this.activated) {

            $(".preloader", this.target$).css("display", "none");

            var images = $(".pageview-group div img", this.target$);

            var lastimage = $(images[images.length - 1]);

            var lastimagediv$ = lastimage.parent();

            var lastimagecontainer$ = lastimagediv$.parent();

            lastimagecontainer$.prepend(lastimagediv$);

            images = $(".pageview-group div img", this.target$).get();

            if (this.isIPhoneIPad() && images.length > 1) {

                images[1].style.display = "block";

                for (var i = 0; i < images.length; i++) {
                    var im = images[i];
                    im.style.display = "block";
                }

                //document.querySelector("#tab").style.display = "block";

            } else {

                var theimage = images[1];

                if (images.length == 1) {
                    theimage = images[0];
                }

                var self = this;

                $(theimage).fadeIn(function() {

                    for (var i = 0; i < images.length; i++) {
                        var im = images[i];
                        im.style.display = "block";
                    }

                    if (self.callback) {
                        self.callback();
                    }

                });
            }

        }

        this.activated = true;


    },

    resizeImages : function() {

        var self = this;

        var total = 0;


        $("img", this.rail$).each(function() {
            total++;
            var imager = self.imageratios[this];
            self.resizeBgImage(imager, $(this));
            if (total == self.numimages) {
                self.activate();
            }
        })

    },

    resizeBgImage : function(bgimager, im$) {

        try {

            if (this.winr > bgimager) {
                im$.css("width", this.ww);
                im$.css("height", "auto");
            } else {
                im$.css("height", this.wh);
                im$.css("width", "auto");
            }

            var iw = im$.width();
            var ih = im$.height();

            var top = (ih - this.wh) / 2;
            var left = (iw - this.ww) / 2;

            im$.css("left", -left + "px");

            im$.css("top", -top + "px");

        } catch (e) {
            alert("resizeBgImage.error: " + e);
        }

    },

    registerIPhoneIPadEvents : function() {
        this.target.addEventListener("touchstart", this, false);
        this.target.addEventListener("touchmove", this, false);
        this.target.addEventListener("touchend", this, false);
    },

    handleEvent : function(event) {

        if (event.type!='touchmove') {
            debug("[E] "+event.type +" "+ this.elapsed());
        }

        switch (event.type) {
            case "webkitTransitionEnd":
                this.moveNodes();
                break;
            case "touchstart":
                if (event.touches[0].pageY < 150) {
                    this.newsFadeIn();
                }
                var handler = event.type + "Handler";
                this[handler](event);
                break;
            case "touchmove":
                if (event.touches[0].pageY < 150) {
                    //this.newsFadeIn();
                }
                var handler = event.type + "Handler";
                this[handler](event);
                break;
            case "touchend":
                var handler = event.type + "Handler";
                this[handler](event);
        }
    },

    getState : function() {
//        debug("[STATE] = "+this.state);
        return this.state;
    },

    setState : function(s, r) {

        if (!r) {
            p = "STATE";
        } else {
            p = r;
        }

        debug("[STATE|"+p+"] "+s);
        this.state = s;
    },

    setOrigin : function(x,y) {
        debug("[O] "+x+":"+y);
        this.originx = x;
        this.originy = y;
    },

    touchstartHandler : function(event) {

        debug("TOUCHSTART");

        if (this.getState() == this.DETACHING) {
            return;
        }

        this.setState(this.ATTACHED, "TOUCHSTART");

        this.setOrigin(event.touches[0].pageX, event.touches[0].pageY);


        this.distancey = 0;
        this.distancex = 0;

        this.dontMove = false;

        event.preventDefault();

    },

    touchmoveHandler : function(event) {
        if (this.getState() != this.ATTACHED) {
            debug("[TOUCHMOVE] NOPE !ATTACHED");
            return;
        }
        var distance = event.touches[0].pageX - this.originx;
        this.distancex = distance;
        this.distancey = event.touches[0].pageY - this.originy;
        //this.group.style.webkitTransform = "translate3d(" + distance + "px, 0, 0)";

    },

    moveLeft : function() {

        var first = this.group.firstChild;

        if (matrix.e < 0) {
            this.group.appendChild(first);
        } else {
            var last = this.group.lastChild;
            this.group.insertBefore(last, first);
        }


    },


    touchendHandler : function(event) {

        if (this.getState() == this.DETACHING) {
            debug("[TOUCHEND] NOPE DETACHING");
            return;
        }

        var matrix =
                new WebKitCSSMatrix(this.group.style.webkitTransform);

        if (this.distancex == 0) {

            this.setState(this.WAITING, "TOUCHEND");

        } else {

            debug("transition end handler " + new Date().getTime());

            var jump = this.target.offsetWidth;

            debug("jump: " + jump);

            debug("matrix.e: " + matrix.e);

            if (Math.abs(this.distancex) < 50) {
                matrix.e = 0;
                this.dontMove = true;
            }

            if (Math.abs(this.distancey) > 300) {
                matrix.e = 0;
                this.dontMove = true;
            }

            if (!this.dontMove) {
                matrix.e = (this.distancex > 0) ? +jump : -jump;
            }

            //matrix.a = (matrix.a > 0) ? +jump : -jump;


            var self = this;

            if (this.dontMove) {

                debug("[TOUCHEND] don't move");

                this.setState("WAITING", "TOUCHEND");

            } else {

                this.group.addEventListener("webkitTransitionEnd", this, false);

                window.setTimeout(function() {

                    self.group.style.webkitTransitionDuration = "";

                    self.group.style.webkitTransitionDelay = "";

                    self.group.style.webkitTransform = matrix;

                }, 10);

                this.setState(this.DETACHING, "TOUCHEND");

            }

        }
    },

    slideLeft : function() {

        var self = this;

        this.rail$.animate({
            left: "-=" + this.ww + "px"
        }, 500, function() {
            var first = self.group.firstChild;
            self.group.appendChild(first);
            self.rail$.css("left", -self.ww);
        })

    },

    slideRight : function() {

        var self = this;

        this.rail$.animate({
            left: "+=" + this.ww + "px"
        }, 500, function() {
            var first = self.group.firstChild;
            var last = self.group.lastChild;
            self.group.insertBefore(last, first);
            self.rail$.css("left", -self.ww);
        })

    },

    moveNodes : function() {

        try {

            debug("[MOVING NODES]");

            var matrix = new WebKitCSSMatrix(this.group.style.webkitTransform);

                var first = this.group.firstChild;

                if (matrix.e < 0) {
                    this.group.appendChild(first);
                } else {
                    var last = this.group.lastChild;
                    this.group.insertBefore(last, first);
                }

            this.group.removeEventListener("webkitTransitionEnd", this, false);

                this.group.style.webkitTransitionDuration = 0;
                this.group.style.webkitTransform = "";

            this.setState(this.WAITING, "MOVENODES");

            this.sendEvent(matrix.e, this.distancey);

        } catch (e) {
            alert("error: " + e);
        }

    }




}


///* The PageView is waiting for a user action */
//PageView.prototype.__defineGetter__("WAITING", function() {
//    return 0
//});
///* The user is pointing to the PageView container */
//PageView.prototype.__defineGetter__("ATTACHED", function() {
//    return 1
//});
///* The user released the container and the PageView is moving to its new position */
//PageView.prototype.__defineGetter__("DETACHING", function() {
//    return 2
//});
//
//PageView.prototype.createElements = function() { /* Create a pages group */
//    //this.target.appendChild(this.group);
//    /* Add the 3 pages */
//}
//
//PageView.prototype.


var view;


function isIPhoneIPad() {
    return navigator.userAgent.match(/(ipad|iphone)/i);
}

var color = 0;

function makeColor(hue) {
    return "hsl(" + hue + ", 100%, 50%)";
}

var debugcount = 1;

function debug(msg) {
//    console.log(debugcount+"| "+msg + ", " + (new Date().getTime() - base));
//    debugcount++;
    return;
    var d$ = $("<div>");
    d$.text(msg)
    $("#info").append(d$);
    d$.get()[0].scrollIntoView();
}

var base = new Date().getTime();

