$(function(){
  
    var data = {};

    if (!("console" in window)) {
        window.console = {
            log:   function () {},
            debug: function () {},
            warn:  function () {},
            error: function () {}
        };
    }

  // Bind an event to window.onhashchange that, when the history state changes,
  // gets the url from the hash and displays either our cached content or fetches
  // new content to be displayed.
  $(window).bind( 'hashchange', function(e) {
    
	  
	  $('.hide-msg').trigger('click'); 
	  
    // Get the hash (fragment) as a string, with any leading # removed. Note that
    // in jQuery 1.4, you should use e.fragment instead of $.param.fragment().
	// Catching #! instead of only # here
    var url = e.fragment.substring(1);
    var urlParams = url.split('/');

//    // takoj redirektam, č evidim da je zahtevan root url
//    if(urlParams[1] == '/' || urlParams[1] == ''){
//        if(document.location.host == 'www.microhint.com') {
//            window.location = 'http://page.microhint.com';   // hack
//        }
//        else if(document.location.host == 'abc.microhint.com') {
//            window.location = 'http://abc.page.microhint.com';   // hack
//        }
//        else {
//            window.location = 'http://page'+document.location.host;   // hack
//        }
//        return false;
//    }


    // "_trackEvent" is the pageview event, 
    _gaq.push(['_trackPageview', url]);

    // If the url hasn't changed, do nothing and skip to the next .bbq widget.
    if ( data.url === url ) { return false; }
    else if(url === '') { url = '/browse_micropons'; urlParams[1] = 'browse_micropons'; }
    
    
    // Store the url for the next time around.
    data.url = url;
    
    // ## Set cookie
    if(urlParams[1] == 'r' && (urlParams[2] != undefined || urlParams[2] != null || urlParams[2] != ''))
    {
    	if($.cookie("_mhref") == undefined)
    	{
    		// IF cookie doesn't exist create one for 3 days
    		$.cookie('_mhref', urlParams[2], {path:'/', domain: 'microhint.com', expires: 3});
    	}
    }
    
    // ## Set layout
    if(urlParams[4] == 'p' || urlParams[4] == 'redeems-print') 
    {
    	MHT.layout.togglePrintWebLayout('print');
    }
    else 
    {
    	MHT.layout.togglePrintWebLayout('web');
    }
    
    
    MHT.page.generate(url);
    return false;
    
  });

  // Init methods
  MHT.dialoglogic.init();

  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).trigger( 'hashchange' );
  
});
