var Scroller = new Class({
    initialize: function(element, options) {
        var self = this
        options.wheelStops = false
        this.scroll = new Fx.Scroll(element, options)
        this.parent = $(element)
        this.children = $(element).getFirst().getChildren()
        this.current = this.children[0].store("show", "true")
        this.nextButton = options.next
        this.previousButton = options.previous
        this.setWheel()
        this.running = false
        this.scrollTo(this.current)
        return this
    },
    scrollTo: function(where) {
        this.running = true
        this.current = where
        var positions = where.getPosition(this.parent)
        this.scroll.start(positions.x - where.getStyle("width").toInt() - where.getStyle("margin").toInt(), 0).chain(function() { this.running = false }.bind(this))
        if(!where.getNext())
            this.disable("next")
        else
            this.enable("next")
        if(!where.getPrevious())
            this.disable("previous")
        else
            this.enable("previous")
    },
    next: function() {
        if(this.running === true) return
        var next = this.current.getNext()
        var previous = next ? next.getPrevious() : false
        if(next) {
            this.scrollTo(next)
        }
    },
    previous: function() {
        if(this.running === true) return
        var previous = this.current.getPrevious()
        var next = previous ? previous.getNext() : false
        if(previous) {
            this.scrollTo(previous)
        }
    },
    disable: function(button) {
        this[button + "Button"].removeEvents("click").addEvent("click", function(e) {
            new Event(e).preventDefault()
        }).tween("opacity", 0.15)
    },
    enable: function(button) {
        var self = this
        this[button + "Button"].removeEvents("click").addEvent("click", function(e) {
            new Event(e).preventDefault()
            self[button]()
        }).tween("opacity", 1)
    },
    setWheel: function() {
        var self = this
        this.parent.addEvent("mousewheel", function(e) {
            if(e.wheel < 0 && self.current.getNext()) {
                self.next()
            }
            else if(self.current.getPrevious()) {
                self.previous()
            }
        })
    }
})
String.prototype.cleanNonASCII = function() {
    var str = this
    var nonASCII = "()!$'?:,&+-/.ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ"
    var ASCII    = "-------------SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy"
    for(var x = 0; x < ASCII.length; x++) {
    if(str.indexOf(nonASCII[x]) > -1)
        str = str.replace(nonASCII[x], ASCII[x], "g")
    }
    return str
}
var createUsername = function(name) {
    var names = name ? name.cleanNonASCII().replace(/[^\s\w]/g, "").toLowerCase().split(" ") : ["", ""]
    if(!names[1])
        names[1] = ""
    if(names[2]) {
        if(names[2].length < 3 && names[3])
            names[2] = names[3]
        names[1] = names[1].substring(0, 3)
    }
    else {
        names[2] = ""
    }
    var username = names[0] + names[1] + names[2]
    $$("input[name=username]").set("value", username)
    checkUsername(username)
}
var checkUsername = function(username) {
    new Request({
        url: location.href.substring(0, location.href.length - "register".length) + "check/user:" + username,
        method: "get",
        onComplete: function(r) {
            if(r == "true") {
                if($$(".username-error").length == 0) {
                    new Element("p", { "class": "username-error" }).set("html", "J&aacute; existe um usu&aacute;rio com este nome. Por favor, escolha outro.").inject($$("input[name=username]")[0].getParent(), "top")
                }
            }
	    else
		$$("p.username-error").destroy()
        },
        autoCancel: true
    }).send("")
}
var getAddressInfo = function(cep) {
    new Request({
        url: location.href.substring(0, location.href.indexOf("users")) + "cep/ajax",
        method: "post",
        onComplete: fillAddressInfo
    }).send("cep=" + cep.replace(/\D/g, ""))
}

var fillAddressInfo = function(str) {
    var queryString = {}
    str.split("&").each(function(item) {
        qs = item.split("=")
        queryString[qs[0]] = unescape(qs[1] || "").replace("+", " ", "g")
    })
    if(queryString["resultado"] > 0) {
        $$("input[name=address]").set("value", (queryString["tipo_logradouro"] + " " + queryString["logradouro"]).clean())
        $$("input[name=city]").set("value", queryString["cidade"])
        $A($$("select[name=uf]")[0].options).each(function(i, k) {
            if(i.value == queryString["uf"])
              $$("select[name=uf]")[0].selectedIndex = k
        })
    }
    
}

var saveObservation = function(id,observation){
    new Request(
                {url: '/camilawinkler/shop/change_observation',
                method: 'post'
                }
    ).send("id="+id+"&observation="+observation);

}

$(window).addEvent("domready", function() {
    if($("productwrapper"))
        Scroll = new Scroller("productwrapper", {
            next: $("scroll-next"),
            previous: $("scroll-previous")
        })
})
