
/**
* Application
*
* This is the main application file for StarWars
* javascript.
*
* @version 1.0
* @author Matt Kenefick <m.kenefick@bigspaceship.com>
* @project Star Wars
*/

App         =   new (function(){

    // private vars
    var _self               =   this;
    var _defaultController  =   'Main';
    var _routes;

    // public vars
    this.name               =   'App';
    this.controllerHistory  =   [];

    this.views              =   {
        ui:         {}
    };
    this.controllers        =   {};
    this.modules            =   {
        explore:        {
            clonewars:      {}
        }
    };

    this.isIE7or8           =   ($.browser.msie && ($.browser.version == '7.0' || $.browser.version == '8.0'));
    var ieDelay = 0;
    

    this.basil              =   new Basil();
    this.log                =   true;


// ===========================================
// ===== CONSTRUCTOR
// ===========================================

    function App(){
        
        //_self.basil.debug = _self.log;
        _self.basil.debug = false;
        
        _self.basil.complete(_self.init);
		
		
        _self.basil.include(BASEURL + "script/com/jquery/jquery.ui.complete.js");
        _self.basil.include(BASEURL + "script/com/zurb/playground/orbit/jquery.orbit-1.2.3.js");
        _self.basil.include(BASEURL + "script/com/bigspaceship/jquery/jquery.bss_orbit.js");
        
        if( Modernizr.touch )
        {
	       	_self.basil.include( BASEURL + 'script/com/jquery/jquery.touchwipe.1.1.1.js' );
        }

        _self.basil.include(BASEURL + "script/com/bigspaceship/jquery/jquery.applyClasses.js");
        _self.basil.include(BASEURL + "script/com/bigspaceship/utils/Out.js");
        
	_self.basil.include(BASEURL + "script/com/starwars/site/modules/navigation.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/associations.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/block1of3.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/calendar.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/commentsList.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/docs/documentation.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/eventsMonth.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/categoryLanding.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/featuredContent.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/featuredEvents.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/login.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/hero.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/hero-home.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/mediaTabPlayer.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/newsTicker.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/relatedContent.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/tabs.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/thumbnailselector.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/share.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/slideshow.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/orbitPlayer.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/facts.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/contentSelector.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/contentSelectorCallout.js");
        _self.basil.include(BASEURL + "script/com/starwars/site/modules/slideList.js");
    }

// ===========================================
// ===== INIT
// ===========================================

    // this is fired after all elements have been constructed
    this.init       =   function init(){
        if(!_self.log && window['Out']) Out.disableAllLevels();
        
        _self.debug(_self, "Star Wars Application Initiated.");

        _setBrowser();
        
        //DS: init all modules
                
        var classLoadDelay;
        
        if (_self.isIE7or8 ){
        	classLoadDelay = 1;
        }else{
         	classLoadDelay = 0;
        }     
                
                
		$('*[data-jsclass]').each(function (i) {
		    var $obj = $(this);
		    if ($obj.data("jsclass").indexOf("FeaturedContent") > -1 ) {
		    	$obj.applyClasses();
		    } else {
		    	setTimeout(function () { $obj.applyClasses(); }, 20 * (i + 1) * classLoadDelay);
		    }
		});

        //_setRouting();
        //_self.replaceLinks();
        
        _self.replaceLinks();

        $("a.fancy").fancybox({

               'overlayColor' : '#333',
               'titlePosition' : 'over',

               'padding' : 20

        });
        
        var subDelay;
        
        if (_self.isIE7or8 ){
        	subDelay = 500;
        }else{
         	subDelay = 0;
        }
		
		setTimeout(function () {
        	_addLinkswipe();
        	//_addModalBoxes();
        	_onResize();

			$(window).resize(_onResize);
        	
        }, subDelay);



        $('body').css('visibility', 'visible');

        



    };


// ===========================================
// ===== CALLABLE
// ===========================================

    /**
     * debug
     *
     * Globalized debug function that handles what port to send
     * from and if it should be enabled at all.
     *
     * $message     mixed   To log.
     * return       void
     */
    this.debug      =   function debug($ref, $message, $func){
        if(_self.log){
            if(!$message){    
                $message = $ref;
                $ref = this;
            }
            
            if(window['Out'] && $func != 'console.log'){
                if($func){
                    Out[$func]($ref, $message);
                }else{
                    Out.debug($ref, $message);
                }
            }else if(window['console']){
				// disabling extensive console logging
                // console.log($message);
            }
        }else{
            return false;
        }
    };

    this.replaceLinks   =   function replaceLinks(){
        var href, newHref, isLocal;

        // log
        _self.debug("Replacing links with delegates");

        $('body').delegate('a', 'click', function(){
            href    =   $(this).attr('href');
            isLocal =   (href != undefined && href.indexOf(BASEURL) > -1);

            if($(this).hasClass('ajax')){
                if(href.indexOf('#!/') === 0 ){
                    window.location.hash    =   href;

                    return false;
                }else{
                    var newHref;
                        newHref     =   $(this).attr('href').split(BASEURL).join('');
                        newHref     =   '!/' + newHref;

                    //window.location =   newHref;
                    window.location.hash    =   newHref;

                    return false;
                }
            }

        });
    };
    
    this.toggleDimmer = function dimmer($zIndex){
		if(!$zIndex)
    		$zIndex=1000;
    	
    	if ($("#Dimmer").length > 0) {
    		

            $('#Dimmer').fadeOut(function(){
                $("#Dimmer").remove();
            });
    
		}else{
	    	$('.page.content').before('<div id="Dimmer"></div>');
	    	$('#Dimmer').hide();
	        $('#Dimmer').css({
	            position:       'fixed',
	            top:            0,
	            left:           0,
	            width:          '100%',
	            height:         '100%',
	            opacity:        .9,
	            zIndex:         $zIndex
	        });
	        $('#Dimmer').fadeIn();
		}
    }


// ===========================================
// ===== WORKERS
// ===========================================

    function _onResize(){
        if( $(this).width() < 960 ){
            $('body').css('overflow-x', 'auto');
        }else{
            $('body').css('overflow-x','hidden');
        }
    }

    function _addLinkswipe (){
        $('.linkswipe a, a.linkswipe, input.linkswipe.cta.button').each(function(){
            var a       =   $(this);
            var text    =   a.html();

            a.append('<span class="rollover" style="width: 0; display:none;">'+text+'</span>'); //
            var span = a.find('span');

            a.hover(function(){
                if(a.hasClass('cta button')){
                    var w       =   a.width()-5;
                }else if(a.hasClass('external')){
                    var w       =   a.width();
                }else{
                    var w       =   a.outerWidth();
                }
                if( parseInt(span.css('margin-left').replace("px", "")) > 0){
                    w = w - parseInt(span.css('margin-left').replace("px", ""));
                }
                span.show().stop().animate({width: w+'px'}, 200);
                //span.show().css('width', w+'px');
            }, function(){
                span.stop().animate({width: '0px'}, 300, function(){span.hide();});
                //span.show().css('width', '0px').hide();
            });
        });

        //external small logo links e.g. wookiepedia
        $('a.small-logo.cta').each(function(){
            var a       =   $(this).find('span');
            var text    =   a.html();
            var w       =   a.width();

            a.append('<span class="rollover" style="width: 0; display:none;">'+text+'</span>');
            var span = a.find('span');
            $(this).hover(function(){
            	var w       =   a.width();
                span.show().stop().animate({width: w+'px'}, 200);
            }, function(){
                span.stop().animate({width: '0px'}, 300, function(){span.hide();});
            });
        });
        
        
        //nested linkswipes
        $('a.nested-linkswipe').each(function(){
            var a       =   $(this);
            var text    =   a.find('div.linkswipe').html();

            a.find('div.linkswipe').append('<span class="rollover" style="width: 0; display:none;">'+text+'</span>'); //
            var span = a.find('div.linkswipe span');

            a.hover(function(){
                var w       =   a.outerWidth();
                if( parseInt(span.css('margin-left').replace("px", "")) > 0){
                    w 		= w - parseInt(span.css('margin-left').replace("px", ""));
                }else if(a.hasClass('external')){
                    var w   =   a.find('div.linkswipe').width();
                }
                span.show().stop().animate({width: w+'px'}, 200);
                //span.show().css('width', w+'px');
            }, function(){
                span.stop().animate({width: '0px'}, 300, function(){span.hide();});
                //span.show().css('width', '0px').hide();
            });
        });
    
    }
    
    
    
    function _addModalBoxes(){
        
        
        // init all links to open modals:
        $('a.openModalbox').click( function(){
            
            if($(this).hasClass('inline')){
                var modalId =  $(this).attr('href');
                $( modalId ).fadeIn();
            }
        });
        
        //modal functionality:
        $('.modalbox').each( function(){
            var modalbox = $(this);
            modalbox.hide();
            $(this).find('.action_close').click( function(){
                modalbox.fadeOut();
            });  
        });
        
    }
    
    function _setBrowser(){
        var userAgent = navigator.userAgent.toLowerCase();

        // Figure out what browser is being used
        jQuery.browser = {
            version: (userAgent.match( /.+(?:rv|it|ra|ie|me|ve)[\/: ]([\d.]+)/ ) || [])[1],
        
            chrome: /chrome/.test( userAgent ),
            safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
            opera: /opera/.test( userAgent ),
            firefox: /firefox/.test( userAgent ),
            msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        
            mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ),
        
            webkit: $.browser.webkit,
            gecko: /[^like]{4} gecko/.test( userAgent ),
            presto: /presto/.test( userAgent ),
        
            android: /android/.test( userAgent ),
            androidVersion: (userAgent.match( /.+(?:android)[\/: ]([\d.]+)/ ) || [0,0])[1],
        
            iphone: /iphone|ipod/.test( userAgent ),
            iphoneVersion: (userAgent.match( /.+(?:iphone\ os)[\/: ]([\d_]+)/ ) || [0,0])[1].toString().split('_').join('.'),
        
            ipad: /ipad/.test( userAgent ),
            ipadVersion: (userAgent.match( /.+(?:cpu\ os)[\/: ]([\d_]+)/ ) || [0,0])[1].toString().split('_').join('.'),
        
            blackberry: /blackberry/.test( userAgent ),
        
            winMobile: /Windows\ Phone/.test( userAgent ),
            winMobileVersion: (userAgent.match( /.+(?:windows\ phone\ os)[\/: ]([\d_]+)/ ) || [0,0])[1]
        };
        
        jQuery.browser.mobile   =   ($.browser.iphone || $.browser.ipad || $.browser.android || $.browser.blackberry );
    }

// ===========================================
// ===== HANDLERS
// ===========================================

    App();

    $(document).ready(applyPlaceholderTextSupport);
})();

