$(document).ready(function() {
	
	BMF.init();
	
});


var BMF = {

    init: function () {

        $("body").addClass("js-enabled");

        BMF.Pullouts.init();

        BMF.Helpers();

        BMF.Carousel.init();

        BMF.Hero.init();

        BMF.infoHover.whoWeAre("#thisIsWhoWeAre .whoIs", true);

        BMF.infoHover.ourClients("#theseAreOurClients .whoIs", true);

        BMF.BlogAccordian();

        BMF.HomeTweetFeed();
    },

    HomeTweetFeed: function () {
        $(".tweet").tweet({
            username: "BMFAustralia",
            //join_text: "auto",
            avatar_size: 32,
            count: 5,
            template: "{avatar}<div class='tweetcontent'><a href='{user_url}' target='_blank'>{screen_name}</a>: {text}</div>",
            /*auto_join_text_default: "we said,",
            auto_join_text_ed: "we",
            auto_join_text_ing: "we were",
            auto_join_text_reply: "we replied to",
            */
            auto_join_text_url: "we were checking out",
            loading_text: "loading tweets..."
        });
        $('.tweet a').attr('target', '_blank');
    },

    BlogAccordian: function () {

        $('.accordion .head').click(function () {

            $(this).next().toggle();
            return false;
        }).next().hide();
    },

    Helpers: function () {

        /* CSS Helpers */

        $("#homeLatest ul li:nth-child(3n)").addClass("rowEnd");

        $("#footer li:last-child").addClass("last");

        $("#careersListing .row:odd, #contactListing .row:odd, #articles .article:odd").addClass("odd");

        $("#news #articles a.youtube").append("<span></span>");

        /* Popup helpers */

        $("a.popup, a.youtube, a.external", "#content").click(function () {
            window.open($(this).attr("href"), 'bmfWin');
            return false;
        });
    },

    /**
    * backgroundImage(safeOnly)
    * @param bool safeOnly 	when TRUE will only display one of the "safe" background images
    * the safe stylesheets are the background image classes background_5 through to background_10
    */
    backgroundImage: function (safeOnly) {
        var range = [0, 7];

        if (safeOnly === true) {
            //we only want to display backgrounds that are "safe"
            range = [2, 7]
        }

        //set body background image class
        var max = Math.max(range[0], range[1]);
        var min = Math.min(range[0], range[1]);

        var rand = Math.round(min + (Math.random() * (max - min)), 0);
        $("body").addClass("background_" + rand);

    },

    infoHover: {

        options: {
            slideUpSpeed: 200,
            slideDownSpeed: 100
        },


        config: {
            sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
            interval: 50, //polling interval  
            timeout: 100 // number = milliseconds delay before onMouseOut    
        },

        ourClients: function (selector, useDelayedHover) {
            var eventConfig = {
                over: function () {
                    $(this).addClass('hovered');

                    var $showr = $(this).find(".theInfo .inner");

                    $showr.closest('.whoIs').find(".thisIs").show().parent().find(".theInfo").show(0, function () {
                        $showr.slideDown(BMF.infoHover.options.slideDownSpeed);
                    });
                },
                out: function () {
                    var that = this;
                    var $hidr = $(this).find(".theInfo .inner");

                    $hidr.slideUp(BMF.infoHover.options.slideUpSpeed, function () {
                        $(that).removeClass('hovered');
                        $hidr.closest('.whoIs').find(".thisIs").hide().parent().find(".theInfo").hide(0);
                    });

                }
            }

            var config = $.extend(BMF.infoHover.config, eventConfig);

            if (useDelayedHover) {
                $(selector).hoverIntent(config);
            }
            else {
                $(selector).hover(config.over, config.out);
            }
        },


        whoWeAre: function (selector, useDelayedHover) {
            var eventConfig = {
                over: function () {
                    $(this).addClass('hovered');
                    $(this).find(".theInfo .inner").slideDown(BMF.infoHover.options.slideDownSpeed);
                },
                out: function () {
                    that = this;
                    $(this).find(".theInfo .inner").slideUp(BMF.infoHover.options.slideUpSpeed, function () {
                        $(that).removeClass('hovered');
                    });

                }
            }

            var config = $.extend(BMF.infoHover.config, eventConfig);

            if (useDelayedHover) {
                $(selector).hoverIntent(config);
            }
            else {
                $(selector).hover(config.over, config.out);
            }
        }

    },

    Pullouts: {

        options: {
            slideUpSpeed: 200,
            slideDownSpeed: 1000
        },

        init: function () {


            var config = {
                sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
                interval: 10, //polling interval  
                timeout: 10 // number = milliseconds delay before onMouseOut    
            };
            var pulloutsConfig = {
                over: function () {
                    $this = $(this);
                    if ($this.is('p') || $this.find(".inner").is(":animated")) {
                        return false;
                    }

                    if ($this.hasClass('active')) {
                        //BMF.Pullouts.closeActive()
                        return false;
                    }
                    else {
                        BMF.Pullouts.closeActive()
                    }

                    BMF.Pullouts.open($this)



                    return false;
                },
                out: function () {
                    $this = $(this);
                    if ($this.is('p') || $this.find(".inner").is(":animated")) {
                        //return false;
                    }

                    //if ($this.closest('.pullout').hasClass('active')) {
                    //	BMF.Pullouts.closeActive()
                    //	return false;
                    //}
                    //else {
                    BMF.Pullouts.closeActive()
                    //}


                    //BMF.Pullouts.close($this)



                    return false;

                }
            }

            poConfig = $.extend(config, pulloutsConfig);


            $(".pullout").hoverIntent(poConfig);


            //Client info revealer
            var clientInfoConfig = {
                over: function () {
                    $t = $(this);
                    if ($t.find(".revealInner").is(":animated")) {
                        return;
                    }
                    $t.find(".revealInner").addClass('active')
						.slideDown({
						    duration: BMF.Pullouts.options.slideDownSpeed / 2,
						    easing: 'easeInOutQuint'
						});

                },
                out: function () {
                    $this = $(this);
                    $t.find(".revealInner")
						.removeClass('active')
						.slideUp({
						    duration: BMF.Pullouts.options.slideDownSpeed / 2,
						    easing: 'easeInOutQuint'
						});
                },
                timeout: 200
            };
            ciConfig = $.extend(config, clientInfoConfig);
            $("#clientInfo .theInfo").hoverIntent(ciConfig);

        },

        closeActive: function () {

            $(".pullout.active")
				.find(".poExtend .inner")
				.slideUp({
				    duration: BMF.Pullouts.options.slideUpSpeed / 2,
				    easing: 'easeOutCirc',
				    complete: function () {
				        $(this)
							.closest(".pullout.active")
							.removeClass('active')

				    }
				})
				.closest(".pullouts.active")
				.removeClass('active');

        },

        open: function ($el) {

            $el.closest('.pullouts')
				.addClass('active');

            $el.closest('.pullout')
				.addClass('active').find(".poExtend .inner")
				.slideDown({
				    duration: BMF.Pullouts.options.slideDownSpeed / 2,
				    easing: 'easeOutQuint' //'easeOutBounce'
				    /*, 
				    complete: function() {
				    $(this).find('p')
				    .slideDown({
				    duration: BMF.Pullouts.options.slideDownSpeed,
				    easing: 'easeOutQuint',
				    complete: function() { console.log('woo');}

				    });
				    }*/
				});


        }

    },

    Carousel: {

        jCarouselOptions: function () { //needs to be an instantiable 
            this.vertical = true;
            this.visible = 4;
            this.scrollAmount = 1;
            this.speed = 1500;
            this.btnPrev = '.btnPrev';
            this.btnNext = '.btnNext';
            this.mouseWheel = true;
            this.easing = 'easeOutQuint';
            this.wrap = 'circular';
        },


        init: function () {

            c1 = new BMF.Carousel.jCarouselOptions();
            c1.speed = 500;
            c1.btnNext = '.col1 .btnNext';
            c1.btnPrev = '.col1 .btnPrev';

            c2 = new BMF.Carousel.jCarouselOptions();
            c2.speed = 800;
            c2.btnNext = '.col2 .btnNext';
            c2.btnPrev = '.col2 .btnPrev';

            c3 = new BMF.Carousel.jCarouselOptions();
            c3.speed = 1000;
            c3.btnNext = '.col3 .btnNext';
            c3.btnPrev = '.col3 .btnPrev';

            $(".col1 .jCarousel").jCarouselLite(c1);
            $(".col2 .jCarousel").jCarouselLite(c2);
            $(".col3 .jCarousel").jCarouselLite(c3);

            $("#workCarousels .btnPrevBig").click(function () {
                $("#workCarousels .btnPrev").trigger("click");
            });
            $("#workCarousels .btnNextBig").click(function () {
                $("#workCarousels .btnNext").trigger("click");
            });

            workCarousel = new BMF.Carousel.jCarouselOptions();
            workCarousel.visible = 14;
            workCarousel.scroll = 4;
            workCarousel.speed = 2600;
            workCarousel.easing = 'easeOutQuint';
            $("#theCarousel").prepend("<div class='controls'><a class='btnPrev button'>Next</a> <a class='btnNext button'>Previous</a>  </div>");
            $("#theCarousel .carousel").jCarouselLite(workCarousel);

            $(window).scroll(function () {
                var newTop = Math.max(-10, $(window).scrollTop() - 175);
                $("#theCarousel .controls").css({ top: newTop });
            });
        }

    },

    Hero: {

        init: function () {
            var playButton, closeButton;
            $theLink = $("#caseStudyHero #caseStudyHeroImage a");
            if ($theLink.is('a')) {
                playButton = '<div class="playButton"><a href="#">Play</a></div>';
                closeButton = '<div class="close"><a href="#">Close</a></div>';

                $("#caseStudyHero .inner #caseStudyVideo").append(playButton);
                $("#caseStudyHero #caseStudyVideo.caseStudyHeroExtended").append(closeButton);
            }
            // #caseStudyHero
            $("#caseStudyHero .playButton").click(function () {
                $(this).fadeOut(100);
                BMF.Hero.show();
                return false;
            });

            $("#caseStudyHero .close").click(function () {
                $(this).fadeOut(100);
                BMF.Hero.hide();
                return false;
            });
			
			if ($("#caseStudyAudio").is("div")) {
				jwplayer("caseStudyAudio").setup({ 
					flashplayer: "/App_Themes/BMF/flash/player.swf", 
					file: $("#caseStudyAudioHeroImage a").attr("href"), 
					image : $("#caseStudyAudioHeroImage img").attr("src"),
					"controlbar.idlehide": true,
					height: 110, width: 455 
				});
			}
			
			
        },

        show: function () {
            //extend
            newCss = {
                width: 495,
                left: 0,
                background: ''
            }
            //$("#caseStudyHeroImage").slideUp({duration:800, easing:"easeOutQuint"});
            $(".caseStudyHeroExtended").show();
            var params = { allowScriptAccess: "always", allowFullScreen: "true" };
            var atts = { id: "ytplayer", wmode: "transparent" };
            theVideoURL = "http://youtube.com/v/" + $("#caseStudyHeroImage a").attr('id');
            swfobject.embedSWF(theVideoURL + "?fs=1&enablejsapi=1&playerapiid=ytplayer&autoplay=1&showsearch=0&rel=0",
												 "caseStudyHeroExtended", "455", "280", "8", null, null, params, atts);

            $("#caseStudyHeroImage").fadeOut(200);
            $("#caseStudyHero .close").fadeIn(200)

            $("#caseStudyHero .inner").css(newCss).animate({ height: 305 }, { duration: 800, easing: "easeOutQuint", complete: function () { } });

        },

        hide: function () {

            newCss = {
                height: 110,
                left: 20,
                paddingLeft: 0,
                width: 455
            }

            $("#caseStudyHero .inner").css("background", 'transparent');
            $("#caseStudyHero .inner .caseStudyHeroExtended").fadeOut(200)
            $("#caseStudyHero .inner").animate(newCss, { duration: 400, easing: "easeOutQuint" });
            $("#caseStudyHero .playButton").show()
            $("#caseStudyHeroImage").delay(50).fadeIn('normal');

        },

        embedVideo: function () {

        }


    },

    Map: function (location, mapDiv, zoomLevel) {

		var that = this;
		//properties
		this.location = location;
		this.mapDiv = mapDiv;
		this.zoomLevel = zoomLevel;
		this.key = "AvINQPN512Oi19O2Ag06FitKb3D3p7UNhRgwe9_wqdrI9MpOTQoxP-vFmFzKKMGs";
		
		this.init = function() {
			this.bodyWidth = $("body").innerWidth();
			this.render();
			
			$(window).bind("resize orientationchange", function(){
				if (that.bodyWidth !== $("body").innerWidth()) {
					that.bodyWidth = $("body").innerWidth();
					that.centerMap();
				}   
				
			});
			
		};
	
	
		this.getAddress = function() {
			$main = $("#"+this.mapDiv);
			$addr =  $main.find("address");
			
			return {
				"text" : $addr.text(),
				"html" : $addr.html(),
				"title": $main.find("h3").text()
			};
			
		}
		
		this.render = function() {
	
			var that = this;
	
			this.address = this.getAddress();
			
			this.latLng  = new Microsoft.Maps.Location(-33.87054808739817, 151.192993);
			
			this.mapOptions = {
				DashboardColor: "black",
				mapTypeId: Microsoft.Maps.MapTypeId.road,
				center: this.latLng,
				zoom: this.zoomLevel,
				credentials:this.key
			};
			
	
			this.map = new Microsoft.Maps.Map(document.getElementById(this.mapDiv), this.mapOptions);
			this.makeGeocodeRequest();
	
		}
		
		/* Sets the center of the map to the current point of interest */
		this.centerMap = function() {
			this.map.setView({center:this.latLng});
		}
		
	
	
	
		this.makeGeocodeRequest = function() {
			var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + this.address.text + "?output=json&key="+this.key+"&jsonp=?",
				icon,
				that = this;
	
			$.getJSON(geocodeRequest, function(result) {
				if (result && 
					result.resourceSets &&
					result.resourceSets.length > 0 &&
					result.resourceSets[0].resources &&
					result.resourceSets[0].resources.length > 0) {
						// Set the map view using the returned bounding box
		 
						// Add a pushpin at the found location
						that.latLng = new Microsoft.Maps.Location(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1]);
						icon = new Microsoft.Maps.Pushpin(that.latLng, {icon: 'http://www.bmf.com.au/App_Themes/BMF/images/map_icon.png',draggable: false, width:24, height:24}); 			
	
						that.map.entities.push(icon);
						that.map.setView({center:that.latLng});
				}
			});
	
	
		}
	
		
		this.init();
		return this;


    },

    Flash: function (theOptions) {

        this.init = function () {
            this.options = $.extend(this.options, theOptions);

        }

        this.options = {
            path: '',
            embedInto: '',
            width: 0,
            height: 0,
            flashvars: {},
            params: {
                wmode: "transparent"
            },
            expressInstallPath: '/App_Themes/BMF/flash/expressInstall.swf',
            version: "8.0",
            attributes: {},
            callbackFn: null

        }

        this.embed = function () {
            o = $.extend(this.options, theOptions);
            swfobject.embedSWF(o.path, o.embedInto, o.width, o.height, o.version, o.expressInstallPath, o.flashvars, o.params, o.attributes, o.callbackFn);

        }

        this.init();
    }


}


