/**
 * @overview RegionManager.js
 * Components for managing region map.
 * @author Chris Scott
 */
Ext.namespace('BQ.regions');

/**
 * BQ.regions.Map
 * @author Chris Scott
 */
BQ.regions.Map = Ext.extend(Ext.Panel, {

    /**
     * @cfg imgSrc {String} image src
     */
    imgSrc : "/static/images/css_images/regions_map.gif",

    /**
     * @cfg imgWidth {Number} image width [398]
     */
    imgWidth : 398,

    border: true,

    width: 424,

    cls: 'bq-region-map',

    initComponent : function() {
        this.on('render', this.renderMap, this);
        this.on('destroy', function(p) {
            p.ptr.remove();
            p.img.remove();
        });

        BQ.regions.Map.superclass.initComponent.call(this);
    },

    renderMap : function() {
        this.marker = this.el.createChild({
            tag: 'div',
            cls: 'bq-map-marker',
            html: '&nbsp;'
        });

        this.marker.hide();

        var map = this.body.createChild({
            tag: 'map',
            id: this.id + '_map',
            name: 'regions'
        });
        map.on('click', this.onClick, this);

        map.update([
             '<area class="baie-james-et-eeyou-istchee" shape="rect" coords="56,214,160,271" href="baiejames.html" alt="Baie-James">',
             '<area class="baie-james-et-eeyou-istchee" shape="poly" coords="126,295,89,350,21,325,33,276" href="baiejames.html" alt="Eeyou Istchee">',
             '<area class="saguenay-lac-st-jean" shape="poly" coords="163,272,98,359,119,385,166,381" href="saguenaylacstjean.html" alt="Saguenay&mdash;Lac-Saint-Jean">',
             '<area class="abitibi-temiscamingue" shape="poly" coords="13,357,75,358,75,387,55,399,35,402,35,422,11,398,18,419,29,421,9,394" href="abitibi.html" alt="Abitibi-Témiscamingue">',
             '<area class="mauricie" shape="poly" coords="80,361,95,361,119,388,132,387,132,401,127,409,132,420,116,425,97,390,79,389" href="mauricie.html" alt="Mauricie">',
             '<area class="outaouais" shape="poly" coords="37,427,39,402,58,402,64,394,76,392,64,407,71,417,71,431,83,432,85,439,65,444,53,437" href="outaouais.html" alt="Outaouais">',
             '<area class="laurentides" shape="poly" coords="81,393,75,401,68,406,73,428,84,424,88,439,103,444,101,430,91,406,92,396,87,392" href="laurentides.html" alt="Laurentides">',
             '<area class="lanaudiere" shape="poly" coords="97,397,104,407,112,420,116,430,107,439,95,414,94,395" href="lanaudiere.html" alt="Lanaudière">',
             '<area class="quebec" shape="poly" coords="137,388,146,386,154,403,147,414,134,416,132,407" href="quebec.html" alt="Québec">',
             '<area class="charlevoix" shape="poly" coords="150,388,158,398,167,383" href="charlevoix.html" alt="Charlevoix">',
             '<area class="manicouagan" shape="poly" coords="168,298,196,297,202,311,200,329,203,348,170,379" href="manicouagan.html" alt="Manicouagan">',
             '<area class="duplessis" shape="poly" coords="200,297,207,340,322,314,366,276,342,256,308,259,265,257,255,288,168,215,170,296" href="duplessis.html" alt="Duplessis">',
             '<area class="duplessis" shape="poly" coords="204,210,167,212,200,240" href="duplessis.html" alt="Duplessis">',
             '<area class="gaspesie" shape="poly" coords="202,369,212,384,230,378,250,376,262,363,250,352,236,351,218,359" href="gaspesie.html" alt="Gaspésie">',
             '<area class="bas-st-laurent" shape="poly" coords="169,401,180,383,194,371,204,381,196,396,174,404" href="basstlaurent.html" alt="Bas-Saint-Laurent">',
             '<area class="chaudiere-appalaches" shape="poly" coords="140,423,145,424,141,434,150,435,163,437,173,410,164,404" href="chaudiereappalaches.html" alt="Chaudière-Appalaches">',
             '<area class="centre-du-quebec" shape="poly" coords="125,430,135,426,141,429,140,437,130,442,122,433" href="centrequebec.html" alt="Centre-du-Québec">',
             '<area class="cantons-de-l-est" shape="poly" coords="119,460,124,450,137,442,152,440,161,442,153,452,142,458" href="cantonsest.html" alt="Cantons-de-l\'Est">',
             '<area class="monteregie" shape="poly" coords="97,457,104,449,110,443,119,434,127,442,114,455" href="monteregie.html" alt="Montérégie">',

             '<area class="Iles-de-la-madeleine" shape="poly" coords="275,365,275,396,311,402,328,383,322,358,294,361" href="ilesmadeleine.html" alt="Îles-de-la-Madeleine">',

             '<area class="nunavik" shape="poly" coords="45,206,205,205,214,197,249,206,245,139,238,101,179,111" href="nunavik.html" alt="Nunavik">',
             '<area class="nunavik" shape="poly" coords="58,197,177,110,163,59,136,41,113,23,65,20,50,114" href="nunavik.html" alt="Nunavik">',
             '<area class="laval" shape="poly" coords="200,437,204,427,210,419,218,416,229,416,212,433,206,438" href="#map" alt="Laval">',
             '<area class="montreal" shape="poly" coords="193,451,195,445,198,441,207,444,214,441,217,438,220,433,225,426,229,423,227,432,227,436,227,441,224,446,222,450,215,452" href="montreal.html" alt="Montréal">',
        ].join(''));

        // build image
        this.img = this.body.createChild({
            tag: 'img',
            src : this.imgSrc,
            width: this.imgWidth,
            usemap: '#regions'
        });

        // not sure where extra 4 pixels comes from.
        //this.setWidth(this.img.getWidth() + this.img.getMargins('lr') + 4);

        var bubble = new BQ.regions.Bubble({
            id: this.id + '_bubble',
            height: 300,
            //if the bubble isn't mobile, the following style should be applied and the renderTo is changed
            //renderTo: document.body
            renderTo: this.container,
            style: "position:absolute; left: 393px; top:21px;"

        });
        //bubble.el.anchorTo(this.img, 'tl-tr', [-18, 0]);

    },

    onClick : function(ev, node, obj) {
        this.marker.show();
        var region = BQ.Regions.find(function(r) {
            return (r.slug == node.className) ? true : false;
        });

        ev.stopEvent();
        var bubble = Ext.getCmp(this.id + '_bubble');
        bubble.setTitle(region.name);
        this.marker.setXY([ev.getPageX() - (this.marker.getWidth()/2), ev.getPageY()-this.marker.getHeight()]);
        bubble.show(region);

        // good positioning-code for aligning to marker ///////////////////////////
        // var xy = bubble.el.getAlignToXY(this.marker, 'tl-bl?');
        //xy = bubble.el.adjustForConstraints(xy);
        //bubble.el.setXY(xy);

    }
});

/**
 * BQ.regions.Bubble
 * Bubble-popup for Region information
 * @author Chris Scott
 */
BQ.regions.Bubble = Ext.extend(Ext.Panel, {
    controller: '/json/BQARegion',
    actions: {
        load : 'stats'
    },
    shadow: false,
    frame: false,
    width: 207,
    closable: false,
    draggable: false,
    resizable: false,
    title: '&nbsp;',
    border: false,

    /**
     * @cfg {String} templateId [null]
     * id of an XTempalate to use.
     */
    templateId : null,

    // private region
    region : null,

    initComponent : function() {
        this.addClass('bq-regions-bubble');

        this.tpl = new Ext.XTemplate(
            '<tpl for=".">',
                '<a href="{[BQJSConfig.http_prefix]}{[BQJSConfig.search]}{[BQJSConfig.app_regions]}/{slug}"><img src="{img}" /></a>',
                '<ul class="stats">',
                    '<li><a href="{[BQJSConfig.http_prefix]}{[BQJSConfig.search]}{[BQJSConfig.app_regions]}/{slug}/photo">{photo} {[App.t("photos")]}</a></li>',
                    '<li><a href="{[BQJSConfig.http_prefix]}{[BQJSConfig.search]}{[BQJSConfig.app_regions]}/{slug}/video">{video} {[App.t("videos")]}</a></li>',
                 '</ul>',
            '</tpl>'
        );

        this.on('render', function(p) {
            p.el.setOpacity(0);
        });

        // super
        BQ.regions.Bubble.superclass.initComponent.call(this);
    },

    show : function(region) {
        region = region || null;
        if (region != null) {
            /**
             * HACK REGION IMAGE FOR NOW
             *
             */
            //region.img = '/static/images/css_images/region_panel_default_image.jpg';
            /*
             *
             *
             */
            region.img = '/static/images/regions/' + Ext.util.Format.lowercase(region.slug) + '.jpg';

            this.el.fadeIn();

            // contact server for more information...
            App.request({
                url: this.controller + '/' + this.actions.load,
                params: {
                    id: region.id
                },
                method: "GET",
                success : function(res) {
                    // render template
                    var data = (res.data.length > 0) ? res.data.shift() : {photo: 0, video: 0, story: 0};
                    this.tpl.overwrite(this.body, Ext.apply(region, data));
                },
                failure : function(res) {
                    alert('BQ.RegionManager failed to load region ' + region.id);
                },
                scope: this
            });
        }
        else {
            console.error('BQ.RegionManager#show was called with a null region');
            return false;
        }
    }
});


