// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());

var FloatBox = {
    
    hide: function() {
        if (Cookie.read('Elematic.FloatBox.ShownOnce')) return;
        var el = $$('#page-index #hot')[0];
        if (!el) return this;
        el.setStyles({
            height: 0,
            opacity: 0
        });
        return this;
    },
    
    show: function() {
        if (Cookie.read('Elematic.FloatBox.ShownOnce')) return;
        var el = $$('#page-index #hot')[0];
        if (!el) return this;
        el.set('morph', { transition: 'quad:out', duration: 450 });
        el.morph({
            height: 149,
            opacity: 1
        });
        Cookie.write('Elematic.FloatBox.ShownOnce', 1);
        return this;
    }
    
};
 
var Products = {
    
    place: function(where) {
        Products.activate(1);
        if (Browser.Plugins.Flash.version < 9) return;
        var cloud = $$('#guide div.cloud')[0];
        console.log(cloud);
        var lang = (document.body.className.match(/lang-([a-z]+)/) || [])[1];
        if (lang == 'en') lang = '';
        else lang = '_' + lang;
        return new Swiff('/files/elematic/swf/productslider.swf', {
            id: 'elematic',
            container: where,
            width: 600,
            height: 600,
            params: {
                wMode: 'opaque',
                bgcolor: '#fefeff',
                menu: "false",
                scale: "noscale",
                allowScriptAccess: "sameDomain",
                flashvars: Hash.toQueryString({
                    xmlfile1: "/default1.xml" + lang,
                    xmlfile2: "/default2.xml" + lang,
                    xmlfile3: "/default3.xml" + lang,
                    tag: cloud ? cloud.getElements('a').getRandom().href.replace(/^.*?#/, '') : null
                })
            }
        });
    },
    
    jump: function(tag) {
        console.log(tag);
        var flash = document.getElementById('elematic');
        if (!flash) return;
        flash.jumpto(tag);
        
        Products.recordClick(tag);
    },
    
    random: function(cloudIndex) {
        console.log('cloudIndex' +cloudIndex);
        var cloud = $$('#guide div.cloud')[cloudIndex];
        if (!cloud) return;
        Products.jump(cloud.getElements('a').getRandom().href.replace(/^.*?#/, ''));
    },
    
    activate: function(row) {
        --row;
        var clouds = $$('#guide div.cloud');
        var heights = [
            [ 246, 73, 73 ],
            [ 48, 268, 73 ],
            [ 48, 73, 268 ]
        ][row];
        console.log(row);
        for (var i = 0, l = clouds.length; i < l; ++i) {
            var ul = clouds[i].getElement('ul');
            ul.setStyle('overflow', 'hidden');
            ul.setStyle('height', heights[i]);
            var tags = ul.getElements('li');
            tags.sort(function(a, b) {
                return a.className < b.className ? 1 : -1
            });
            if (row == i) {
                ul.addClass('active');
                tags.setStyle('display', 'inline');
            }
            else {
                ul.removeClass('active');
            }
            while (ul.scrollHeight > ul.offsetHeight && tags.length) {
                tags.pop().setStyle('display', 'none');
            }
            for (var li = ul.getLast(); li; li = li.getPrevious()) {
                if (li.getStyle('display') == 'none') continue;
                if (li.offsetTop + li.offsetHeight > ul.offsetHeight - 10) li.setStyle('display', 'none');
                else break;
            }
        }
    },
    
    recordClick: function(tag) {
        console.log(tag);
        new Request({
            url: '/tagclick?ngform_on=1'
        }).post({
            q0: tag
        });
    }
    
};
 
var ContactMap = new Class({
 
    Implements: [ Options ],
    
    options: {
        locationFeed: '/locations.json',
        center: [ 61.178095, 23.869686 ],
        zoom: 3,
        open: null
    },
    
    initialize: function(el, options) {
        if (typeof GBrowserIsCompatible == 'undefined' || !GBrowserIsCompatible()) return this;
        this.bound = {
            onLocationsLoaded: this.onLocationsLoaded.bind(this)
        };
        this.element = $(el);
        this.icons = {
            "1.0": this.createIcon({
                image: '/files/elematic/maps/marker-y-22x34.png',
                iconSize: new GSize(22, 34),
                iconAnchor: new GPoint(11, 33),
                infoWindowAnchor: new GPoint(11, 0)
            }),
            "2.0": this.createIcon({
                image: '/files/elematic/maps/marker-y-22x34.png',
                iconSize: new GSize(22, 34),
                iconAnchor: new GPoint(11, 33),
                infoWindowAnchor: new GPoint(11, 0)
            }),
            "3.0": this.createIcon({
                image: '/files/elematic/maps/marker-y-22x34.png',
                iconSize: new GSize(22, 34),
                iconAnchor: new GPoint(11, 33),
                infoWindowAnchor: new GPoint(11, 0)
            }),
            "4.0": this.createIcon({
                image: '/files/elematic/maps/marker-r-22x34.png',
                iconSize: new GSize(22, 34),
                iconAnchor: new GPoint(11, 33),
                infoWindowAnchor: new GPoint(11, 0)
            }),
            "5.0": this.createIcon({
                image: '/files/elematic/maps/marker-y-22x34.png',
                iconSize: new GSize(22, 34),
                iconAnchor: new GPoint(11, 33),
                infoWindowAnchor: new GPoint(11, 0)
            })
        };
        this.setOptions(options);
        this.locations = [];
        this.map = new GMap2(this.element);
        this.map.addControl(new GLargeMapControl());
        this.map.addControl(new GMapTypeControl());
        this.map.setCenter(new GLatLng(this.options.center[0], this.options.center[1]), this.options.zoom);
        this.ready = false;
        this.load();
    },
    
    createIcon: function(options) {
        var icon = new GIcon(G_DEFAULT_ICON);
        Hash.extend(icon, options);
        return icon;
    },
    
    createInfo: function(loc) {
        return [
            '<div class="gmap-info-window" style="font-size: 8pt; line-height: normal">',
                '<h2 style="font-size: 140%; font-weight: bold; font-family: Arial, Verdana, Helvetica, sans-serif; margin: 0 0 1em 0;">',
                    loc.location_name,
                '</h2>',
                '<h3 style="font-size: 100%; font-weight: bold; color: #ff0000; margin: 0">',
                    '<a href="/location?id=', loc.pid, '">',
                        loc.classification_name,
                    '</a>',
                '</h3>',
                loc.tel ? [ '<span class="tel">Tel. ',
                    loc.tel,
                '</span>' ].join('') : '',
                '<div class="adr">',
                    loc.contact_information,
                '</div>',
                loc.classification == '5.0' ? [ '<br /><span class="gps">GPS: ',
                    loc.latlng,
                '</span>' ].join('') : '',
            '</div>'
        ].join('');
    },
    
    createMarker: function(loc) {
        var marker = new GMarker(loc.point, {
            icon: this.icons[loc.classification],
            title: loc.location_name
        });
        marker.info = this.createInfo(loc);
        marker.bindInfoWindowHtml(marker.info);
        loc.marker = marker;
        return marker;
    },
    
    load: function() {
        new Request.JSON({
            url: this.options.locationFeed,
            onComplete: this.bound.onLocationsLoaded
        }).get({
            ts: $time()
        });
    },
    
    onLocationsLoaded: function(data) {
        var map = {};
        $each(data.result, function(loc) {
            var latlng = loc.latlng.split(',', 2);
            loc.point = new GLatLng(latlng[0], latlng[1]);
            map[loc.pid] = loc;
        });
        this.locations = map;
        this.populate();
    },
    
    open: function(pid) {
        if (!this.ready) {
            this.options.open = pid;
            return;
        }
        if (!pid) return;
        var loc = this.locations[pid];
        if (!loc) return;
        loc.marker.openInfoWindowHtml(loc.marker.info);
    },
    
    populate: function() {
        $each(this.locations, function(loc) {
            this.map.addOverlay(this.createMarker(loc));
        }, this);
        this.ready = true;
        this.open(this.options.open);
    }
    
});
 
var Polaroid = new function() {
    
    var activeAnchor;
    var polaroidElement;
    var topElement, contentElement, bottomElement, pictureElement, descriptionElement;
    
    function shareOver() {
        return addthis_open(this, '', activeAnchor.href, activeAnchor.title);
    }
    
    function share() {
        addthis_sendto();
        return false;
    }
    
    function shareOut() {
        addthis_close();
        return false;
    }
    
    function send() {
        location.href = '/send?link=' + encodeURIComponent(activeAnchor.href) + '&title=' + encodeURIComponent(activeAnchor.title);
        return false;
    }
    
    function display() {
        polaroidElement.inject(document.body).set('opacity', 0).fade('in');
        return false;
    }
    
    function hide() {
        polaroidElement.fade('out').get('tween').chain(function() {
            polaroidElement.dispose();
        });
        return false;
    }
    
    function actions() {
        return new Element('div', {
            'class': 'actions'
        })
        .adopt(new Element('a', {
            text: 'Share',
            href: '#add',
            'class': 'share',
            events: {
                click: share,
                mouseout: shareOut,
                mouseover: shareOver
            }
        }))
        .adopt(new Element('a', {
            text: 'Send',
            href: '#send',
            'class': 'send',
            events: {
                click: send
            }
        }))
        .adopt(new Element('a', {
            text: 'Close',
            href: '#close',
            'class': 'close',
            events: {
                click: hide
            }
        }));
    }
    
    function update() {
        var title = activeAnchor.get('title') || '';
        descriptionElement.setStyle('display', title.length ? 'block' : 'none');
        descriptionElement.set('text', title);
        pictureElement.setStyle('background-image', 'none').addClass('picture-loading');
        var img = new Image();
        img.onload = function() {
            var avail = window.getHeight() - 150;
            pictureElement.removeClass('picture-loading').setStyles({
                'background-image': 'url(' + img.src + ')',
                height: Math.min(avail, img.height)
            });
            polaroidElement.setStyle('margin-top', -polaroidElement.getHeight() / 2);
        };
        img.src = activeAnchor.href;
    }
 
    polaroidElement = new Element('div', {
            'class': 'polaroid'
        })
        .adopt(topElement = new Element('div', {
            'class': 'top'
        }))
        .adopt(contentElement = new Element('div', {
            'class': 'content'
            })
            .adopt(pictureElement = new Element('div', {
                'class': 'picture'
            }))
            .adopt(descriptionElement = new Element('div', {
                'class': 'description'
            }))
            .adopt(actions()))
        .adopt(bottomElement = new Element('div', {
            'class': 'bottom'
        }));
    
    this.show = function() {
        activeAnchor = this;
        update();
        display();
        return false;
    };
    
};
 
var PopUp = new function() {
    
    var externalSource;
    var polaroidElement;
    var topElement, contentElement, bottomElement, frameElement;
 
    function display() {
        polaroidElement.inject(document.body).set('opacity', 0).fade('in');
        return false;
    }
    
    function hide() {
        polaroidElement.fade('out').get('tween').chain(function() {
            polaroidElement.dispose();
        });
        return false;
    }
    
    function actions() {
        return new Element('div', {
            'class': 'actions'
        })
        .adopt(new Element('a', {
            text: 'Close',
            href: '#close',
            'class': 'close',
            events: {
                click: hide
            }
        }));
    }
    
    function update() {
        frameElement.src = externalSource;
    }
 
    polaroidElement = new Element('div', {
            'class': 'polaroid'
        })
        .adopt(topElement = new Element('div', {
            'class': 'top'
        }))
        .adopt(contentElement = new Element('div', {
            'class': 'content'
            })
            .adopt(frameElement = new Element('iframe', {
                'class': 'external',
                border: 0,
                frameborder: 0,
                scrolling: 'no'
            }))
            .adopt(actions()))
        .adopt(bottomElement = new Element('div', {
            'class': 'bottom'
        }));
    
    this.show = function() {
        externalSource = this.href;
        update();
        display();
        return false;
    };
    
};
 
function em(to) {
    var parts = to.split('/', 2);
    var start = parseInt(parts[1].charAt(2), 10);
    var end = parseInt(parts[1].charAt(3), 10);
    var mail = parts[1].substring(start, parts[1].length - end).replace(/;/g, '.') + '@' + parts[0];
    document.write('<a href="mailto:' + mail + '" class="email">' + mail + '</a>');
}
 
 
// tip a            
var tipa = {
    
    hide: function() {
        
        var el = $$('.tippi')[0];
        if (!el) return this;
        el.setStyles({
            opacity: 0
        });
        return this;
    },
    
    show: function() {
        
        var el = $$('.tippi')[0];
        if (!el) return this;
        el.morph({
            opacity: 10
        });
        return this;
    }
    
};
 
// tip b
var tipb = {
    
    hide: function() {
        
        var el = $$('.tippi2')[0];
        if (!el) return this;
        el.setStyles({
            opacity: 0
        });
        return this;
    },
    
    show: function() {
        
        var el = $$('.tippi2')[0];
        if (!el) return this;
        el.morph({
            opacity: 10
        });
        return this;
    }
    
};        
 
//tip c
var tipc = {
    
    hide: function() {
        
        var el = $$('.tippi3')[0];
        if (!el) return this;
        el.setStyles({
            opacity: 0
        });
        return this;
    },
    
    show: function() {
        
        var el = $$('.tippi3')[0];
        if (!el) return this;
        el.morph({
            opacity: 10
        });
        return this;
    }
    
};    
 
window.init = function() {
    
    
    // dup :(
    
    $$('.tblstyle1 td:first-child').addClass('first');
    $$('.tblstyle1 td:last-child').addClass('last');
    $$('.tblstyle1 td:empty').set('html', '&nbsp;');
 
    (function() {
        
        $$('#products .cloud a').addEvent('click', function(e) {
            e.stop();
            Products.jump(this.href.replace(/^.*#/, ''));
        });
        
        $$('#products .cloud h3').addEvent('click', function(e) {
            e.stop();
            var tag = this.getParent().getElement('a');
            if (!tag) return;
            Products.jump(tag.href.replace(/^.*#/, ''));
        });
    
        $$('.nav li').addEvents({
            mouseenter: function(e) {
                e.stop();
                //$$('.nav li').removeClass('hover');
                this.addClass('hover');
            },
            mouseleave: function() {
                this.removeClass('hover');
            }
        });
    
        $$('#guide').addEvents({
            mouseover: function() {
                $$('.nav li').removeClass('hover');
            }
        });
        
        $$('.locales a').addEvent('click', function(e) {
            e.stop();
            var rel = $(this.get('rel'));
            rel.addClass('loading');
            var lang = this.get('hreflang');
            this.getParent('ul').getChildren('li').removeClass('active');
            this.getParent('li').addClass('active');
            new Request({
                url: this.get('data-source'),
                onSuccess: function(response) {
                    rel.removeClass('loading');
                    rel.set('html', response);
                    rel.getElements('.pictures a.picture').addEvent('click', Polaroid.show);
                    rel.getElements('.popup').addEvent('click', PopUp.show);
                }
            }).get({ ts: $time() });
        });
        
        $$('.collapsible > li').addEvent('click', function(e) {
            if ($(e.target).hasClass('toggle')) {
                e.stop();
                this.toggleClass('collapsed');
                return;
            }
            if ($(e.target).hasClass('dyn')) e.stop();
        });
    
        $$('.pictures a.picture').addEvent('click', Polaroid.show);
    
        $$('.popup').addEvent('click', PopUp.show);
        
    }).delay(10);
    
    
// hiding dem
tipa.hide();
tipb.hide();
tipc.hide();
 
//tip a
$$('.tips').addEvent('mouseenter', function(){
  tipa.hide().show();
});
 
$$('.tips').addEvent('mouseleave', function(){
  tipa.hide();
});
 
//tip b
$$('.tips2').addEvent('mouseenter', function(){
  tipb.hide().show();
});
$$('.tips2').addEvent('mouseleave', function(){
  tipb.hide();
});
 
//tip c
$$('.tips3').addEvent('mouseenter', function(){
  tipc.hide().show();
});
$$('.tips3').addEvent('mouseleave', function(){
  tipc.hide();
});
 
 
// CUFON
Cufon.set('hover', 'true');
Cufon.replace('h1', { fontFamily: 'thesans' });
Cufon.replace('h2', { fontFamily: 'thesans' });
Cufon.replace('#nav', { fontFamily: 'thesans' });
Cufon.replace('#box-about .box-content', { fontFamily: 'thesans' });
Cufon.replace('#hot #fsearch label', { fontFamily: 'thesanslight' });
Cufon.replace('#hot #fsearch button', { fontFamily: 'thesans' });
Cufon.replace('.tip .text', { fontFamily: 'thesans' });
Cufon.replace('.lift_content', { fontFamily: 'thesans' });
Cufon.replace('.lift_footer', { fontFamily: 'thesans' });
Cufon.replace('#info h2', { fontFamily: 'thesanslight' })
 
 
};
