(function ($, window, document) {

    (function($,sr){

        // debouncing function from John Hann
        // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
        var debounce = function (func, threshold, execAsap) {
            var timeout;

            return function debounced () {
                var obj = this, args = arguments;
                function delayed () {
                    if (!execAsap)
                        func.apply(obj, args);
                    timeout = null; 
                }

                if (timeout)
                    clearTimeout(timeout);
                else if (execAsap)
                    func.apply(obj, args);

                timeout = setTimeout(delayed, threshold || 100); 
            };
        };

        // smartresize 
        jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

    })(jQuery,'smartresize');



    $(document).ready(function() {    
        
        
        // apply to all pages on resize
        function allPages() {
            if ($(window).width() > 1023) {
                // open all external links in the main content area in new windows / tabs, but only for larger screens / devices
                $("div.main a[href^='http'], div.sponsors a[href^='http']")
                .attr('target','_blank');
                //.after('<img class="external-link" src="/img/icons/external.png" alt="External Link" />');
            } else {
                $("div.main a[href^='http']").attr('target','');
            }
            
            // Fix mobile Safari orientation
            var viewportmeta = document.querySelector && document.querySelector('meta[name="viewport"]'),
                ua = navigator.userAgent,

                gestureStart = function () {
                    viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
                },

                scaleFix = function () {
                  if (viewportmeta && /iPhone|iPad/.test(ua) && !/Opera Mini/.test(ua)) {
                    viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
                    document.addEventListener("gesturestart", gestureStart, false);
                  }
                };
            scaleFix();
        }
        
        
        
        function home() {
            // speaker images not clickable
            $('.featuring li a').css('cursor', 'default').click(function() {
               return false; 
            });

            // Countdown
            var date = $('.buy-tickets dl dt time.end-date').attr('datetime');
            var countdown = new Date(date);
            
            $('.buy-tickets dl dt time.end-date').remove();
            $('.buy-tickets dl dt').countdown({until: countdown, format: 'DHMS', layout:'<time datetime="'+countdown+'" class="days">{dnn}<span>days</span></time><time datetime="'+countdown+'" class="hours">{hnn}<span>hours</span></time><time datetime="'+countdown+'" class="minutes">{mnn}<span>minutes</span></time><time datetime="'+countdown+'" class="seconds">{snn}<span>seconds</span></time>'});
            
            // Carousel
            if ($(window).width() > 1023) {
            	$('.featuring ul').carouFredSel({
            		width: $('.featuring ul').parents('.featuring').innerWidth(),
                	scroll: {
                	    items: 6,
                	},
                	auto: {
                	    duration        : 2500,
                	    pauseDuration   : 5000,
                	}
                });
            } else {
                $('.featuring ul').trigger('destroy');
            }
        }
        
        
        
        // set up the schedule table
        function schedule() {
            // only fire our function if the res < 1023px
            if ($(window).width() > 1023) {
                // reset, otherwise window resizing will keep stacking up event listeners
                $('div.schedule section ul li dl').removeClass('show').find('dt').unbind('click');
                // Find the boxes that need to be collapsible, and add a class of 'hide' to the dl
				$('div.schedule section ul li dl').addClass('hide');
				// Hide the dds
				$('div.schedule section ul li dl.hide dd').hide();
				// Toggle the visibility of the dds
				$('div.schedule section ul li dl.hide dt').click(function(){
					$(this).parent().toggleClass('show');
					$(this).parent().find('dd').slideToggle('slow');
					return false;
			   });
            } else {
                $('div.schedule section ul li dl').removeClass('hide').unbind;
                $('div.schedule section ul li dl dd').show();
            }
        }
        
         // set up the fancy schedule table
        function fancySchedule() {
            // only fire our function if the res < 1023px
            if ($(window).width() > 1023) {
                
                // var numDays = $('li.day').length;
                // var numTracks = $('#day2 ul.track').length;
                // var numSessions = $('#day2 .track-one li.session').length;
                // 
                // console.log('Days: '+numDays);
                // console.log('Tracks: '+numTracks);
                // console.log('Sessions: '+numSessions);
                // 
                // var d = 1;
                // var s = 1;
                // 
                // for (d=1;d<=numDays;d++) {
                // 
                //     console.log('day'+d);
                // 
                //     $('.schedule #day'+d+' ul.track').carouFredSel({
                //         circular : false,
                //      infinite    : false,
                //      items   : 4,
                //      scroll  : 1,
                //      width   : 870,
                //      auto    : false,
                //      prev    : '.schedule-wrapper .prev',
                //      next    : '.schedule-wrapper .next',
                //     });
                // }
                
                // reset, otherwise window resizing will keep stacking up event listeners
                $('ul.schedule li ul li').removeClass('show').find('dl dd dl dt').unbind('click');
                // Find the boxes that need to be collapsible, and add a class of 'hide' to the dl
				$('ul.schedule li ul li').not('.break').addClass('hide');
				// Hide the dds
				$('ul.schedule li ul li.hide dl dd dl dd').hide();
				// Toggle the visibility of the dds
				$('ul.schedule li ul li').not('.break').click(function(){
					$(this).toggleClass('show');
					$(this).find('dl dd dl dd').toggle();
					return false;
			   });
			   // For all track two sessions that follow breaks, add the class after-break
			   $('ul.schedule li ul li.break + li.session').addClass('after-break');
            } else {
                $('ul.schedule li ul li dl dd dl').removeClass('hide').unbind;
                $('ul.schedule li ul li.session').removeClass('hide').unbind;
                $('ul.schedule li ul li dl dd dl').show();
            }
        }
        
        
        
        // store the ticket list (we might need to replace the tickets table when resized)
        if ($('body#register').length) {
            var tickets_list = $('section.ticket-types');
        }
        
        // set up the register layout switch / amiando integration
        function register() {
            // only fire our function if the res < 1023px
            if ($(window).width() > 1023) {
                
                // add in amiando iframe if it doesn't already exist, along with click handlers
                if (!$('#amiando').length) {
                    
                    // scroll to amiando iframe
                    $('ul.tickets dl a').click(function() {
                        $('html, body').animate({
                            scrollTop: $('#amiando').offset().top
                        }, 1500);
                        return false;
                    });
                    
                    // get amiando url - need to work out a way of generating iframe automatically...
                    var amiando_url = $('.ticket-buy h3 a.button').attr('href');
                    
                    // append amiando iframe (amiando JS script is in footer)
                    $('ul.tickets').after('<div id="amiando"><iframe src="https://www.amiando.com/fowdlondon2012.html?viewType=iframe&panelId=1222322&useDefaults=false&resizeIFrame=true" frameborder="0" width="650px" height="450px" name="_amiandoIFrame12223227hxzC0bs" id="_amiandoIFrame12223227hxzC0bs"><p>This page requires frame support. Please use a frame compatible browser to see the amiando ticket sales widget.</p><p> Try out the <a href="http://www.amiando.com/">online event registration system</a> from amiando.</p></iframe><p style="text-align: left; font-size:10px;"><a href="http://www.amiando.com" target="_blank" alt="conference - Online Event Management" title="conference - Online Event Management" >conference - Online Event Management</a> with the ticketing solution from amiando</p></div>');
                    
                    $('#amiando').append('<img class="loading" src="/img/graphics/loading.gif" />');
                    $('#amiando iframe').load(function() {
        				$('#amiando .loading').remove();
        		    });
                } else {
                    // amiando already exists but is hidden, so just show it
                    $('#amiando').show();
                }
            } else {
                // hide amiando if it already exists, we don't want to remove it & then re-add it on window resize (otherwise it breaks amiando JS script)
                if ($('#amiando').length) {
                    $('#amiando').hide();
                }
            }
        }
        
        
        
        // function venue() {
        //     // only fire our function if the res < 1023px
        //     if ($(window).width() > 1023) {
        //         function googleMaps() {
        //                 $('#locations li div.map-holder').each(function() {
        //                 var map = $(this).find('a.map');
        // 
        //                 map.attr('src', map.attr("href")) // Inserts the link attribute in the embed attribute
        //                    .removeAttr("href") // Removes href attribute
        //                    .find('img').remove(); // Remove all map images
        // 
        //                 var src = map.attr("src");
        //                 var title = map.attr("title");
        // 
        //                 map.replaceWith('<iframe></iframe>');
        // 
        //                 var iframe = $(this).find('iframe');
        //                 iframe.attr('class', 'map') // Gives the iframe a class of 'map'
        //                       .attr('src', src) // Gives the iframe the embed code of the previous link
        //                       .attr('title', title) // Gives the iframe the title of the previous link
        //                       .attr('width', '440') // Makes the iframe 440px wide
        //                       .attr('height', '270') // Makes the iframe 270px tall
        //                       .attr('frameborder', '0') // No frameborder on the iframe
        //                       .attr('scrolling', 'no') // No scrolling on the iframe
        //                       .attr('marginheight', '0') // No margin height on the iframe
        //                       .attr('marginwidth', '0') // No margin width on the iframe
        //                       .attr('src',iframe.attr('src').replace('source=embed', 'output=embed'));
        // 
        //                 // above is a great example of method chaining with jQuery, where we don't
        //                 // have to keep reusing our selector
        // 
        //             });
        //         }
        //     } else {
        //         
        //     }
        // }
        
        

        // set up a window resize selector
        $(window).smartresize(function() {
            allPages();
            
            if ($('body#schedule').length) {
               fancySchedule(); 
            };
            
            if ($('body#register').length) {
                register();
            }
            
            if ($('body#home').length) {
                home();
            }
            
            // if ($('body#venue').length) {
            //     venue();
            // }
        });


        // trigger the resize for the first time
        $(window).trigger('resize');

    });

}(jQuery, this, this.document));
