/*
 * Unobtrusive scripting adapter for OutFront
 *
 *
 * Copyright 2011 Landlord Web Solutions. All rights reserved.
 * http://www.landlordwebsolutions.com
 *
 */

var OutFront = (function() {

    // _map
    // _bounds
    // _markers
    // _infoWindow
    // _latlng
    // _names

    function OutFront() {

        // Constructor

    }

    OutFront.prototype.run = function() {
        this.installLightboxes();
        this.installGalleria();
        this.installMaps();
        this.installDatePickers();
        this.installCitySelects();
    };

    // -----------------------------------------------------------------
    // GOOGLE MAPS (PLOTTING APARTMENTS)
    // -----------------------------------------------------------------

    OutFront.prototype.installMaps = function() {
        if ($('#map').length > 0) {
            this.loadMapScripts();
        }
    };

    /*
     * LoadMapScripts
     * --------------
     * Unlike the other lazyloaded scripts, this one uses a true callback
     * which calls function that is inserted into the document as per
     * Google's recommendation.
     */

    OutFront.prototype.loadMapScripts = function() {
        var s = document.createElement("script");

        s.type = "text/javascript";
        s.src = "http://maps.google.com/maps/api/js?v=3&sensor=true&callback=gmap_draw";

        window.gmap_draw = function() {

            var outFront = new OutFront();
            if ($('html.ie6').length < 1 && $('html.ie7').length < 1) {
                //IF not IE6 or IE7 prep map for animation after load
               outFront.styleMap();
            }
            outFront.createMap();

        };

        $('head').append(s);
    };

    /*
     * styleMap
     * --------
     * Applies basic styles to the map
     */

    OutFront.prototype.styleMap = function() {

        var m = $('#map');
        var mw = $('#map-wrapper');
        var w = m.attr('data-width');
        var h = 0;

        m.css({
            'width' : w + 'px',
            'height' : h + 'px',
            'display' : 'block',
            'opacity' : 0
        });

        mw.css({
            'display' : 'block',
            'opacity' : 0
        });

    };

    /*
     * CreateMap
     * ---------
     * Creates a map placeholder and begins the process of replacing it
     * with an actual map.
     */

    OutFront.prototype.createMap = function() {

        var m = $('#map');
        var w = m.attr('data-width');
        var h = m.attr('data-height');


        m.animate({

                    height: h

                }, 500, 'linear', function() {
                    OutFront.prototype.initializeMap();

                });

    };

    /*
     * initializeMap
     * ------------
     * Creates an instance of a Google Map in the page
     */

    OutFront.prototype.initializeMap = function() {

        var m = $('#map');
        var w = m.attr('data-width');
        var h = m.attr('data-height');

        this._latlng = new google.maps.LatLng(43.1849669, -79.2002143);

        var options = {

            zoom : 8,
            center : this._latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP

        };

        this._map = new google.maps.Map(document.getElementById('map'), options);
        this._bounds = new google.maps.LatLngBounds();
        this._markers = new Array();
        this._infoWindow = new google.maps.InfoWindow({});
        this._zoom = 8;

        if ($('html.ie6').length < 1 && $('html.ie7').length < 1) {
           this.revealMap();
        } else {
           this.markerMap();
        }


    };

    /*
     * revealMap
     * --------
     * Animates the map into view. Orchestrates placement of markers.
     */

    OutFront.prototype.revealMap = function() {

        var m = $('#map');
        var mw = $('#map-wrapper');

        mw.animate({

                    opacity: 1.0

                }, 200, 'linear', function() {


                    if ($('article.apartment').length < 1) {
                        var lat = $(this).attr('data-latitude');
                        var lng = $(this).attr('data-longitude');

                        if (lat && lng) {

                            var pos = new google.maps.LatLng(lat, lng);
                            this._bounds.extend(pos);

                            this._latlng = pos;

                            this._map.fitBounds(_bounds);

                        }
                    }

                    m.animate({

                        opacity: 1.0

                    }, 200, 'linear', function() {

                         OutFront.prototype.markerMap();

                    });


                });


    };

    /*
     * markerMap
     * ---------
     * Iterates apartment data to find locations. Places markers on
     * map at those locations.
     */

    OutFront.prototype.markerMap = function() {

        $('article.apartment').each(function() {

            var t = $(this);

            var name = t.attr('data-name') || '';
            var street_number = t.attr('data-street_number') || '';
            var street_name = t.attr('data-street_name') || '';
            var city = t.attr('data-city') || '';
            var province = t.attr('data-province') || '';
            var postal = t.attr('data-postal') || '';
            var country = t.attr('data-country') || '';
            var phone = t.attr('data-phone') || '';
            var path = t.attr('data-path') || '';
            var latitude = t.attr('data-latitude') || '';
            var longitude = t.attr('data-longitude') || '';
            var link_title = t.attr('data-link-title') || '';

            if (latitude && longitude) {
                var position = new google.maps.LatLng(latitude, longitude);
                OutFront.prototype._bounds.extend(position);
            }

            var infoString = '<div class="gMap" style="overflow:hidden; width: auto; height:auto;">';
            infoString += '<h4 style="font-size: 12px; line-height: 1em; margin: 0; margin-bottom: 1em; padding: 0; border: none;"><b><a href="' + path + '">' + name + '</a></b></h4>';
            infoString += '<p style="font-size: 10px; line-height: 1.1em; margin: 0; padding: 0; border: none;">';
            infoString += street_number + ' ' + street_name + '<br>';
            infoString += city + ', ' + province + ' ' + postal + '<br><br>';
            infoString += '<b>' + phone + ' <br> <a href="' + path + '">'+link_title+'</b>';
            infoString += '</p>';

            var marker = new google.maps.Marker({
                map: OutFront.prototype._map,
                draggable: true,
                animation: google.maps.Animation.DROP,
                position: position
            });

            var infoWindow = new google.maps.InfoWindow({
                content: infoString
            });

            google.maps.event.addListener(marker, 'click', function() {
                infoWindow.open(OutFront.prototype._map, marker);
            });

        });

        this._map.fitBounds(this._bounds);

		var zl = this._map.getZoom();
        if (zl > 15) {
            this._map.setZoom(15);
        }
       
        if ($('html.ie6').length < 1 && $('html.ie7').length < 1) {
        	//set latlng to the center pos so When tab is clicked we can resize and center (helps rerender of map within tabs);
        	this._latlng = this._map.getCenter();
        	this._zoom = this._map.getZoom();
		} else {
			this._latlng = this._bounds.getCenter();
        	this._zoom = this._map.getZoom();
		}
    };

    // -----------------------------------------------------------------
    // FORM ENHANCEMENTS
    // -----------------------------------------------------------------

    /*
     * InstallDatePickers
     * -----------------
     * Converts text input into dropdown calendar for choosing a date.
     */
     
    OutFront.prototype.installDatePickers = function() {
      
      $object = $('#calendar');
      $trigger = $('.input-move-in-date input');
      
      $object.wijcalendar({
        popupMode: true,
        selectedDatesChanged: function() {
            var selDate = $(this).wijcalendar('getSelectedDate');
            if (selDate) $trigger.val(selDate.getFullYear() +'-'+ (selDate.getMonth()+1)+'-'+selDate.getDate());
        }
      });
      
      $trigger.click(function() {
        $object.wijcalendar('popup', { of: $trigger, offset: '0.2' });
      });
    
    };

    /*
     * InstallCitySelects
     * ------------------
     * Creates dynamic city select boxes.
     */

    OutFront.prototype.installCitySelects = function() {

        if ($('.city-select').length <= 0) return;

        var bi_fields = $('.require-b-i');

        var ci = $('p.input-cities');

        var bi = $('p.input-buildings');
        var bis = $('select.building-select');
        var bso = $('select.building-select option');

        var original_building_options = bso;

        var cs = $('.city-select');

        var is_inquiry = $('input:radio[name=is_building_inquiry]');

        if (is_inquiry.filter(':checked').val() == 1) {

            ci.css({'display': 'block'});

            bi_fields.css({'display': 'block'});

            cs.trigger('change');

        } else {
            ci.css({'display': 'none'});

            bi.css({'display':'none'});

            bi_fields.css({'display': 'none'});
        }

        is_inquiry.change(function() {

            var inquiry = is_inquiry.filter(':checked').val();

            if (inquiry == 1) {

                ci.css({'display': 'block'});

                bi_fields.css({'display': 'block'});

            } else {

                cs.val(-1);

                cs.trigger('change');

                ci.css({'display': 'none'});

                bi_fields.css({'display': 'none'});

            }
        });

        cs.live('change', function() {

            var t = $(this);

            var city_id = t.val();

            if (city_id < 0) {

                bi.css({ 'display' : 'none' });

            } else {

                bi.css({ 'display' : 'block' });

            }

            original_building_options.each(function(index) {
                bis.append(this);
            });
            bso.each(function(index) {

                var u = $(this);

                if (parseInt(u.val()) < 0) {

                    u.attr('selected', true);

                } else {

                    u.attr('selected', false);

                }

                if (u.attr('data-city-id') != city_id && u.val() != -1) {

                    u.remove();

                } else {

                    u.css({'display' : 'block' });

                }

            });

        });

    };

    // -----------------------------------------------------------------
    // GALLERIA JQUERY PLUGIN
    // -----------------------------------------------------------------

    /*
     * installGalleria
     * ---------------
     * Checks document for instance of Galleria, loads dependencies and
     * binds elements.
     */

    OutFront.prototype.installGalleria = function() {

        if ($('[data-galleria="true"]').length <= 0) return;
        this.showLoader(true);

        if ($('[data-galleria-type="classic"]').length > 0) {

            this.loadGalleriaClassicStyles();

        } else if ($('[data-galleria-type="twelve"]').length > 0) {

            this.loadGalleriaTwelveStyles();

        }

    };

    /*
     * showLoader
     * ----------
     * Places a loader in parent element of the Galleria
     */
    OutFront.prototype.showLoader = function(showIt) {
        if (showIt === true) {
            $('[data-galleria="true"]').parent().css({
                //backgroundImage: 'url('+_base_path+'styles/libs/galleria-classic-1.2.3/classic-loader.gif)',
                backgroundColor: '#161616'
                // backgroundPosition: '-18px 11px',
                // backgroundRepeat: 'no-repeat',
            });
        } else {
            $('[data-galleria="true"]').parent().css({
                // backgroundImage: 'none',
                backgroundColor: 'transparent'
            });
        }
    };

    /*
     * loadGalleriaClassicStyles
     * -------------------------
     * Load the styles for Galleria classic.
     */

    OutFront.prototype.loadGalleriaClassicStyles = function() {

        var src = _base_path + "styles/libs/galleria-classic-1.2.3/galleria.classic.css";
        OutFront.prototype.lazyLoadStyle(src, OutFront.prototype.loadGalleriaClassicDependencyScripts);

    };

    /*
     * loadGalleriaTwelveStyles
     * ------------------------
     * Loads the styles for Galleria twelve theme.
     */

    OutFront.prototype.loadGalleriaTwelveStyles = function() {

        var src = _base_path + "styles/libs/galleria-twelve-1.2.3/galleria.twelve.css";
        OutFront.prototype.lazyLoadStyle(src, OutFront.prototype.loadGalleriaTwelveDependencyScripts);

    };

    /*
     * loadGalleriaClassicDependencyScripts
     * -----------------------------------
     * Loads the dependencies for galleria classic theme.
     */

    OutFront.prototype.loadGalleriaClassicDependencyScripts = function() {

        var src = _base_path + "scripts/libs/galleria-1.2.3.min.js";
        OutFront.prototype.lazyLoadScript(src, OutFront.prototype.loadGalleriaClassicScripts);

    };

    /*
     * LoadGalleriaTwelveDependencyScripts
     * -----------------------------------
     * Loads the dependencies for the galleria twelve theme.
     */

    OutFront.prototype.loadGalleriaTwelveDependencyScripts = function() {

        var src = _base_path + "scripts/libs/galleria-1.2.3.min.js";
        OutFront.prototype.lazyLoadScript(src, OutFront.prototype.loadGalleriaTwelveScripts);

    };

    /*
     * LoadGalleriaClassicScripts
     * --------------------------
     * Loads the galleria classic theme
     */

    OutFront.prototype.loadGalleriaClassicScripts = function() {
        var src = _base_path + "scripts/libs/galleria.classic.js";
        OutFront.prototype.lazyLoadScript(src, OutFront.prototype.bindGalleria);
    };

    /*
     * LoadGalleriaTwelveScripts
     * -------------------------
     * Loads the galleria twelve theme
     */

    OutFront.prototype.loadGalleriaTwelveScripts = function() {
        var src = _base_path + "scripts/libs/galleria.twelve.min.js";
        OutFront.prototype.lazyLoadScript(src, OutFront.prototype.bindGalleria);
    };

    /*
     * BindGalleria
     * ------------
     * Binds galleria plugin to elements with their galleria data-attr flagged as true.
     */

    OutFront.prototype.bindGalleria = function() {

        $('div#galleria').show();

        var w = 500;
        var h = 500;

        if ($('[data-galleria-width]').length > 0) {
            var item = $('[data-galleria-width]');
            w = item.attr('data-galleria-width');
        }

        if ($('[data-galleria-height]').length > 0) {
            var item = $('[data-galleria-height]');
            h = item.attr('data-galleria-height');
        }

        $('[data-galleria="true"]').galleria({
            width: parseInt(w),
            height: parseInt(h),
            transition: 'fade',
            transitionSpeed: 0,
            extend: function(options) {
                OutFront.prototype.showLoader(false);
            }
        });

    };

    // -----------------------------------------------------------------
    // LIGHTBOX/FANCYBOX JQUERY PLUGINS
    // -----------------------------------------------------------------

    /*
     * InstallLightboxes
     * -----------------
     * Checks document for instances of lightboxes, loads dependencies, and
     * binds elements.
     */

    OutFront.prototype.installLightboxes = function() {

        var lightboxes = new Array();

        if ($('[data-lightbox-type="fancybox"]').length > 0) {

            $('[data-lightbox-type="fancybox"]').each(function(index) {
                if (index == 0) {
                    lightboxes.push($(this).attr('data-lightbox-name'));
                } else {
                    for (var i = 0; i < lightboxes.length; i++) {
                        if ($(this).attr('data-lightbox-name') != lightboxes[i]) {
                            lightboxes.push($(this).attr('data-lightbox-name'));
                        }
                    }
                }
                if (index == $('[data-lightbox-type="fancybox"]').length - 1) {
                    var variant = $('[data-lightbox-type="fancybox"]').attr('data-lightbox-variant');
                    var version = $('[data-lightbox-type="fancybox"]').attr('data-lightbox-version');
                    OutFront.prototype.loadFancyBoxStyles({lightboxes: lightboxes, variant: variant, version: version});
                }
            });

        }

    };

    /*
     * LoadFancyBoxStyles
     * ------------------
     * Loads the styles for FancyBox and provides a callback function that
     * will load the FancyBox scripts once the styles have completed
     * loading. This ensures proper execution of FancyBox.
     */

    OutFront.prototype.loadFancyBoxStyles = function(options) {
        var src = _base_path + "styles/libs/jquery.fancybox/jquery.fancybox-" + options.version + "-variant-" + options.variant + ".css";
        OutFront.prototype.lazyLoadStyle(src, OutFront.prototype.loadFancyBoxScripts, options);

    };

    /*
     * LoadFancyBoxScripts
     * -------------------
     * Loads the scripts for FancyBox and provides a callback function that
     * will bind Fancybox once the scripts have completed loading. This
     * ensures proper execution of FancyBox.
     */

    OutFront.prototype.loadFancyBoxScripts = function(options) {
        var src = _base_path + "scripts/libs/jquery.fancybox-" + options.version + ".pack.js";
        OutFront.prototype.lazyLoadScript(src, OutFront.prototype.bindFancyBox, options);
    };

    /*
     * BindFancyBox
     * ------------
     * Binds FancyBox plugin to elements with their lightbox data attribute
     * flagged as true.
     */

    OutFront.prototype.bindFancyBox = function(options) {

        var items = options.lightboxes;

        for (var i = 0; i < items.length; i++) {

            var item = $('[data-lightbox-name="'+items[i]+'"]');

            if (item.attr('data-scrolling') === 'auto') {
                scrolling = auto;
            } else {
                scrolling = item.attr('data-scrolling') === 'true';
            }

            var options = {
                'padding': parseInt(item.attr('data-padding')) || 50,
                'margin': parseInt(item.attr('data-margin')) || 20,
                'opacity': parseFloat(item.attr('data-opacity')) || 0.3,
                'modal': item.attr('data-modal') === true,
                'cyclic': item.attr('data-cyclic') === true,
                'scrolling': item.attr('data-scrolling') === scrolling,
                'width': parseInt(item.attr('data-width')) || 560,
                'height': parseInt(item.attr('data-height')) || 340,
                'autoScale': item.attr('data-auto-scale') === 'true',
                'autoDimensions': item.attr('data-auto-dimensions') === 'true',
                'centerOnScroll': item.attr('data-center-on-scroll') === 'true',
                'hideOnOverlayClick': item.attr('data-hide-on-overlay-click') === 'true',
                'hideOnContentClick': item.attr('data-hide-on-content-click') === 'true',
                'overlayShow': item.attr('data-overlay-show') === 'true',
                'titleShow': item.attr('data-title-show') === 'true',
                'titlePosition': item.attr('data-title-position') || 'outside',
                'transitionIn': item.attr('data-transition-in') || 'fade',
                'transitionOut': item.attr('data-transition-out') || 'fade',
                'speedIn': parseInt(item.attr('data-speed-in')) || 300,
                'speedOut': parseInt(item.attr('data-speed-out')) || 300,
                'changeSpeed': parseInt(item.attr('data-change-speed')) || 300,
                'changeFade': item.attr('data-change-fade') || 'fast',
                'easingIn': item.attr('data-easing-in') || 'swing',
                'easingOut':item.attr('data-easing-out') || 'swing',
                'showCloseButton': item.attr('data-show-close-button') === 'true',
                'showNavArrows': item.attr('data-show-nav-arrows') === 'true',
                'enableEscapeButton': item.attr('data-enable-escape-button') === 'true'
            };

            if (item.attr('data-title-format')) {
                options.titleFormat = item.attr('data-title-format');
            }

            if (item.attr('data-title')) {
                options.title = item.attr('data-title');
            }

            if (item.attr('data-href')) {
                options.href = item.attr('data-href');
            }

            if (item.attr('data-type')) {
                options.type = item.attr('data-type');
            }

            if (item.attr('data-content')) {
                options.type = item.attr('data-content');
            }

            if (item.attr('data-orig')) {
                options.type = item.attr('data-orig');
            }

            if (item.attr('data-index')) {
                options.type = item.attr('data-index');
            }

            if (item.attr('data-ajax')) {
                options.ajax = item.attr('data-ajax');
            }

            if (item.attr('data-swf')) {
                options.swf = item.atr('data-swf');
            }

            if (item.attr('data-on-start')) {
                options.onStart = function() {
                    var fn = window[item.attr('data-on-start')];
                }
            }

            if (item.attr('data-on-cancel')) {
                options.onCancel = function() {
                    var fn = window[item.attr('data-on-cancel')];
                    fn();
                }
            }

            if (item.attr('data-on-complete')) {
                options.onComplete = function() {
                    var fn = window[item.attr('data-on-complete')];
                    fn();
                }
            }

            if (item.attr('data-on-cleanup')) {
                options.onCleanup = function() {
                    var fn = window[item.attr('data-on-cleanup')];
                    fn();
                }
            }

            if (item.attr('data-on-closed')) {
                options.onClosed = function() {
                    var fn = window[item.attr('data-on-closed')];
                    fn();
                }
            }
            
            item.fancybox(options);

        }

    };

    /*
     * LazyLoadScript
     * -------------
     * A thin wrapper around the script loading function in the lazy load library.
     */

    OutFront.prototype.lazyLoadScript = function(src, action, options) {
        LazyLoad.js(src, function(arg) {
            if (options) {
                action(options);
            } else {
                action();
            }
        }, 'Loaded script: ' + src);
    };

    /*
     * LazyLoadStyle
     * -------------
     * A thin wrapper around the style loading function in the lazy load library.
     */

    OutFront.prototype.lazyLoadStyle = function(src, action, options) {
        LazyLoad.css(src, function(arg) {
            if (options) {
                action(options);
            } else {
                action();
            }
        }, 'Loaded style: ' + src);
    };

    return OutFront;

})();

$(document).ready(function() {
    var outfront = new OutFront();
    outfront.run();
});

