// detect browser engine
var Engine = {
    detect: function() {
        var UA = navigator.userAgent;
        this.isKHTML = /Konqueror|Safari|KHTML/.test(UA);
        this.isGecko = (/Gecko/.test(UA) && !this.isKHTML);
        this.isOpera = /Opera/.test(UA);
        this.isMSIE  = (/MSIE/.test(UA) && !this.isOpera);
        this.isMSIE7 = this.isMSIE && !(/MSIE 6\./.test(UA) && !this.isOpera);
    }
};
Engine.detect();

// prototype extension to allow mousewheel capture
Object.extend(Event, {
    wheel:function (event){
        var delta = 0;
        if (!event) event = window.event;
        if (event.wheelDelta) {
            delta = event.wheelDelta/120;
            if (window.opera) delta = -delta;
        }
        else
            if (event.detail) delta = -event.detail/3;
        return Math.round(delta); //Safari Round
    }
});

// prototype extension to allow onReady (before onload)
Object.extend(Event, {
    _domReady : function() {
        if (arguments.callee.done) return;
        arguments.callee.done = true;
        if (Event._timer)  clearInterval(Event._timer);
        Event._readyCallbacks.each(function(f) { f() });
        Event._readyCallbacks = null;
    },
    onReady : function(f) {
        if (!this._readyCallbacks) {
            var domReady = this._domReady;
            if (domReady.done) return f();
            if (document.addEventListener)
            document.addEventListener("DOMContentLoaded", domReady, false);
            /*@cc_on @*/
            /*@if (@_win32)
            document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
            document.getElementById("__ie_onload").onreadystatechange = function() {
                if (this.readyState == "complete") { domReady(); }
            };
            /*@end @*/
            if (/WebKit/i.test(navigator.userAgent)) { 
                this._timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState)) domReady(); 
                }, 10);
            }
            Event.observe(window, 'load', domReady);
            Event._readyCallbacks = [];
        }
        Event._readyCallbacks.push(f);
    }
});

// simple carrousel effect
Effect.BackgroundScroll = Class.create();
Object.extend(Object.extend(Effect.BackgroundScroll.prototype, Effect.Base.prototype), {
    initialize: function(element) {
        this.element = $(element);
        var backgroundPosition = this.element.style.backgroundPosition.split(' ');
        this.element.currentBackgroundPosition = [parseInt(backgroundPosition[0].replace('px','')), parseInt(backgroundPosition[1].replace('px',''))];
        this.offsets = arguments[1];
        this.start(arguments[2] || {});
    },
    setup: function() {
        this.current = this.element.currentBackgroundPosition;
        this.delta = [this.offsets[0] - this.current[0], this.offsets[1] - this.current[1]];
    },
    update: function(position) {
        this.element.currentBackgroundPosition = [Math.round(this.current[0] + (this.delta[0]*position)), Math.round(this.current[1] + (this.delta[1]*position))];
        this.element.style.backgroundPosition = this.element.currentBackgroundPosition[0] + 'px ' + this.element.currentBackgroundPosition[1] + 'px';
    }
});

// on dom load, initialize elements
Event.onReady(function() {
    ['who_image', 'services_image', 'where_image', 'contact_image'].concat($$('#who .bubble'), $$('#services_links img')).each(function(element) {
        $(element).setOpacity(0)
    });
    ['ecatalogue', 'eshop', 'ebusiness', 'elogistic', 'software'].each(function(element) {
        new Draggable(element, {revert:true})
    });
    ['who_icon', 'services_icon', 'where_icon', 'contact_icon'].each(function(element) {
        $(element).setStyle({cursor:'move'})
    });
    $('location').setStyle({cursor:'pointer'})
});

// on page load, make effects
Event.observe(window, 'load', function() {
    $$('#who .bubble').each(function(element, index) {
        Effect.Appear(element,{delay:index*.3, beforeStart:function(effect){effect.element.setStyle({visibility:''})}})
    });
    ['who_image', 'services_image', 'where_image', 'contact_image'].each(appear_from_background);
    $$('#services_links img').each(function(element, index) {
        Effect.Appear(element, {delay:index*.5, beforeStart:function(effect){effect.element.setStyle({visibility:''})}})
    });
    interactive_map();
});

// smooth appear icons
function appear_from_background() {
    var element = arguments[0];
    new Effect.Scale(element, 100, {
        beforeStart:function(effect) {
            effect.element.setStyle({visibility:''})
        },
        afterUpdate:function(effect) {
            $(effect.element).setOpacity(effect.position)
        },
        afterFinish:function(effect) {
            new Draggable($(element).up(), {revert:true})
        },
        duration: .5,
        scaleFrom: 0,
        scaleFromCenter: true,
        queue:{
            scope: 'main',
            position: 'end'
        }
    });

}

// changes the plain map to a web map service
var map;
var pointLatLng;
function interactive_map() {
    map = new GMap2($('map'));;
    var geocoder = new GClientGeocoder();;
    geocoder.getLatLng('Aragó 208, Barcelona, Spain', function(point) {
        pointLatLng = point;
        map.setCenter(pointLatLng, 16);
        map.addControl(new GMapTypeControl());
		map.addControl(new GSmallZoomControl());
        var marker = new GMarker(point);
        map.addOverlay(marker);
    });
    ['mousewheel', 'DOMMouseScroll'].each( function(event) {
        $('map').observe(event, function(event) {
            if(Event.wheel(event) > 0) map.zoomIn();
            else map.zoomOut();
            Event.stop(event)
        });
    });
}

// gets the info from the clicked service
var executing_effect = false;
function show_service_information(href) {
    if(!executing_effect) {
        executing_effect = true;
        if($('services_box_content'))
            new Effect.Parallel([Effect.Fade('services_box'), Effect.BlindUp('services_box')], {
                afterFinish: function() {
                    new Ajax.Updater('services_box', 'http://aggelosnet.com?content=1&asection=' + href, {
                        onComplete: show_services_box
                    });
                }
            });
        else
        {
            new Ajax.Updater('services_box', 'http://aggelosnet.com?asection=' + href, {
                onLoading: function() {
                    $('services_box').hide()
                },
                onComplete: show_services_box
            });
        }
    }
}

// shows the service box with the information of the clicked service
function show_services_box() {
    new Effect.Parallel([Effect.Appear('services_box'), Effect.BlindDown('services_box')], {
        afterFinish: function() {
            executing_effect = false;
        }
    });
}

// go to the given coordinates on the image
function go_to_image(coordinates, element) {
    var displace = {x: 450, y:350};
    new Effect.BackgroundScroll('carrousel', [displace.x * -coordinates[1], displace.y * -coordinates[0]], {duration: 1.5});
    $A($('carrousel_links').getElementsByTagName('a')).each(function(link) {
        $(link).removeClassName('selected')
    });
    element.addClassName('selected')
}
