(function(window, undefined) {

var GG = {
    init: function() {
        // Load <body> class name and load views.
        this.views._global.call(this);
        var classNames = document.body.className.split(" ");
        for (var i=0; classNames[i]; i++) {
            if (this.views[classNames[i]]) {
                this.views[classNames[i]].call(this);
            }
        }
    },

    parseVideo: function(url, dimensions) {
        var m = dimensions.match(/^(\d+)x(\d+)$/);
        if (m) {
            var width = m[1];
            var height = m[2];
        } else {
            return;
        }
        var provider = null;
        var id = null;
        if (/https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)/.test(url)) {
            provider = "http://www.youtube.com/v/";
            id = /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&amp;(?:amp;)?)*v(?:&lt;[A-Z]+&gt;)?=([0-9a-zA-Z\-\_]+))/i.exec(url)[2];
        } else if (/https?:\/\/(?:[a-zA_Z]{2,3}.)?vimeo.com\/(\d*)/.test(url)) {
            provider = "http://vimeo.com/moogaloop.swf?clip_id=";
            id = url.match(/https?:\/\/(?:[a-zA_Z]{2,3}.)?vimeo.com\/(\d*)/)[1];
        } else {
            return;
        }
        swfobject.embedSWF(provider + id, "art-video", width, height, "9.0.0");
    },

    views: {
        '_global': function() {
            
            $("#nav-main a:path").addClass("active");
            $("form.login .field input").each(function(){
                var label_text = $(this).prev("label").hide().text();
                $(this).attr("placeholder",label_text.replace("*",""));
            });
            $("input[placeholder]").placeholder();
            
            if(Aino.IE && Aino.IE < 9) {
                
                $("#nav-main a").each(function() {
                   $(this).corner("tr tl 5px");
                });
            }
        },
        'cart': function() {
           $(".delete a").bind("click", function() {
               $(this).parent().siblings(".count").find("input").val("0")
               $("#cart-form").submit();
           });
        },
        'contact': function() {
            $(".collapse").collapse({
                head: '.summary h3',
                group: '.detail'
            });
        },
        'locators': function() {
            $(".collapse").collapse({
                head: '.summary h3',
                group: '.detail'
            });
        },
        'payment-summary' : function() {
            
            $("#terms-of-delivery").click(function(e) {
                e.preventDefault();
                Aino.modal.set('loading...').show({
                    focus: true,
                    clickOutside: true
                });
                $.get(this.href,
                function(data) {
                    Aino.modal.set(data);
                });
            });
        },
        'buy': function() {
            $('input.buy').each(function(index, value) {
                $(value).click(function(e) {
                    e.preventDefault();
                    var form = $(e.target).closest('form');
                    $.ajax({
                        data: form.serialize(),
                        dataType: 'json',
                        type: 'POST',
                        success: function(data, textStatus, XMLHttpRequest) {
                            for (selector in data['html']) {
                                $(selector).html(data['html'][selector]);
                            }
                            // XXX make a nicer alert
                            alert(data['message']);
                        }
                    })
                });
            });
        },
        'list-view': function() {
            var toggle = $("#toggle-display");
            var link = toggle.find("a");
            var list = $("#primary .boxes");
            toggle.click(function(e) {
                e.preventDefault();
                link.toggleClass("active");
                list.toggleClass("list");
            });
            (function(q, articles) {
               var data = {},
                   find,
                   title,
                   matches,
                   elem,
                   stripped,
                   speed = 200;
               $.each(articles, function(i, article) {
                   data[i] = $(article).find('h2 a').text();
               });
               q.val('').focus().bind('keyup', function(e) {
                   if (q.val().length > 1) {
                       find = new RegExp(q.val().toLowerCase());
                       $.each(articles, function(i, article) {
                           title   = data[i];
                           elem    = $(article).find('h2 a');
                           matches = find.exec(data[i].toLowerCase());
                           if (! matches) {
                               elem.text(data[i]);
                               $(article).hide(speed);
                           } else {
                               $(article).show(speed)
                               stripped = data[i].substr(0, matches.index) +
                                          '<strong>' +
                                          data[i].substr(matches.index, q.val().length) +
                                          '</strong>' +
                                          data[i].substr((q.val().length + matches.index));
                               elem.html(stripped);
                           }
                       })
                   } else {
                       articles.filter(function() {
                           return $(this).is(':hidden');
                       }).show(speed).end().find('h2 a').each(function(i) {
                           $(this).text(data[i]);
                       });
                   }
               })
           })($('#filter'), $('.boxes').children());
        },
        map: function() {
            //
            // create the infowindow to show the markers info in
            var infowindow = new google.maps.InfoWindow({
                size: new google.maps.Size(50,50),
                maxWidth: 250
            });
            var options = {
                disableDefaultUI: true,
                navigationControl: true,
                scrollwheel: false,
                mapTypeId: google.maps.MapTypeId.HYBRID
            };
            var map = new google.maps.Map(document.getElementById("map"), options);
            var icon = JSTOOLS.settings.MEDIA_URL + 'i/map/gron_24x24.png';
            //
            // creates the marker
            var createMarker = function(loc) {
                var position = new google.maps.LatLng(loc.lat, loc.lon);
                var marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    icon: icon
                });
                var content = '<div class="info-window"><h2>' + loc.title + '</h2>' + loc.content;
                content += loc.url ? ' <a href="' +  loc.url + '">Läs mer</a>' : '';
                content += '</div>';
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.close();
                    infowindow.setContent(content);
                    infowindow.open(map, marker);
                });
            }
            for(var j=0; j < FARM_LOCATIONS.length; j++) {
                createMarker(FARM_LOCATIONS[j]);
            }
            //
            // set bounding box to show all markers
            var sw = new google.maps.LatLng(EXTREMES.minLat, EXTREMES.minLon);
            var ne = new google.maps.LatLng(EXTREMES.maxLat, EXTREMES.maxLon);
            var bounds = new google.maps.LatLngBounds(sw, ne);
            map.fitBounds(bounds);
        }
    }
}

window.GG = GG;

})(window);

