var debug = false

try {document.execCommand( 'BackgroundImageCache', false, true )} catch( error ) {}
try {history.navigationMode = 'compatible'} catch( error ) {}

var Hash = (function () {
var
// Import globals
window = this,
documentMode = document.documentMode,
history = window.history,
location = window.location,
// Plugin variables
callback, hash,
// IE-specific
iframe,

getHash = function () {
    // Internet Explorer 6 (and possibly other browsers) extracts the query
    // string out of the location.hash property into the location.search
    // property, so we can't rely on it. The location.search property can't be
    // relied on either, since if the URL contains a real query string, that's
    // what it will be set to. The only way to get the whole hash is to parse
    // it from the location.href property.
    //
    // Another thing to note is that in Internet Explorer 6 and 7 (and possibly
    // other browsers), subsequent hashes are removed from the location.href
    // (and location.hash) property if the location.search property is set.
    //
    // Via Aaron: Firefox 3.5 (and below?) always unescape location.hash which
    // causes poll to fire the hashchange event twice on escaped hashes. This is
    // because the hash variable (escaped) will not match location.hash
    // (unescaped.) The only consistent option is to rely completely on
    // location.href.
    var index = location.href.indexOf('#');
    return (index == -1 ? '' : location.href.substr(index + 1));
},

// Used by all browsers except Internet Explorer 7 and below.
poll = function () {
    var curHash = getHash();
    if (curHash != hash) {
        hash = curHash;
        callback(curHash, false);
    }
},

// Used to create a history entry with a value in the iframe.
setIframe = function (newHash) {
    try {
        var doc = iframe.contentWindow.document;
        doc.open();
        doc.write('<html><body>' + newHash + '</body></html>');
        doc.close();
        hash = newHash;
    } catch (e) {
        setTimeout(function () {setIframe(newHash);}, 10);
    }
},

// Used by Internet Explorer 7 and below to set up an iframe that keeps track
// of history changes.
setUpIframe = function () {
    // Don't run until access to the iframe is allowed.
    try {
        iframe.contentWindow.document;
    } catch (e) {
        setTimeout(setUpIframe, 10);
        return;
    }

    // Create a history entry for the initial state.
    setIframe(hash);
    var data = hash;

    setInterval(function () {
        var curData, curHash;

        try {
            curData = iframe.contentWindow.document.body.innerText;
            if (curData != data) {
                data = curData;
                location.hash = hash = curData;
                callback(curData, true);
            } else {
                curHash = getHash();
                if (curHash != hash) setIframe(curHash);
            }
        } catch (e) {
        }
    }, 50);
};

return {
    init: function (cb, ifr) {
        // init can only be called once.
        if (callback) return;

        callback = cb;

        // Keep track of the hash value.
        hash = getHash();
        cb(hash, true);

        // Run specific code for Internet Explorer.
        if (window.ActiveXObject) {
            if (!documentMode || documentMode < 8) {
                // Internet Explorer 5.5/6/7 need an iframe for history
                // support.
                iframe = ifr;
                setUpIframe();
            } else  {
                // Internet Explorer 8 has onhashchange event.
                window.attachEvent('onhashchange', poll);
            }
        } else {
            // Change Opera navigation mode to improve history support.
            if (history.navigationMode) history.navigationMode = 'compatible';

            setInterval(poll, 50);
        }
    },

    go: function (newHash) {
        // Cancel if the new hash is the same as the current one, since there
        // is no cross-browser way to keep track of navigation to the exact
        // same hash multiple times in a row. A wrapper can handle this by
        // adding an incrementing counter to the end of the hash.
        if (newHash == hash) return;
        if (iframe) {
            setIframe(newHash);
        } else {
            location.hash = hash = newHash;
            callback(newHash, false);
        }
    }
};
})();

(function (jQuery, Hash) {
var iframeId = 'jquery-history',
    iframeSrc = '/js/blank.html',
    eventName = 'hashchange',
    eventDataName = 'hash.fn',
    init,
    // Import globals
    window = this,
    documentMode = document.documentMode,

    // Called whenever the hash changes.
    callback = function (newHash) {
        jQuery.event.trigger(eventName, [newHash]);
    };

jQuery.hash = {
    init: function (src) {
        // init can only be called once.
        if (init) return;
        init = 1;

        var iframe;
        if (window.ActiveXObject && (!documentMode || documentMode < 8)) {
            // Create an iframe for Internet Explorer 7 and below.
            jQuery('body').prepend(
                '<iframe id="' + iframeId + '" style="display:none;" ' +
                'src="' + (src || iframeSrc) + '"></iframe>');
            iframe = jQuery('#' + iframeId)[0];
        }

        Hash.init(callback, iframe);
    },

    go: Hash.go
};

jQuery.fn.hash = function (newHash, changeHref) {
    var fn = this.data(eventDataName);
    if (fn) this.unbind('click', fn);

    if (typeof newHash == 'string') {
        fn = function () {Hash.go(newHash);return false;};
        this.data(eventDataName, fn);
        this.click(fn);
        if (changeHref || changeHref === undefined)
            this.attr('href', '#' + newHash);
    }

    return this;
};

jQuery.fn[eventName] = function (fn) {
    return this.bind(eventName, fn);
};
})(jQuery, Hash);


jQuery.fn.onImagesLoaded = function(_cb) {

    return this.each(function() {

        var $imgs = ( this.tagName.toLowerCase() === 'img' ) ? $( this ) : $( 'img' , this ) ,

            _cont = this,

            i = 0,

            _done = function () {
                preloader()
                if( typeof _cb === 'function' ) _cb(_cont);
            }


        if( $imgs.length ) {

            $imgs.each( function() {

                var _img = this,

                _checki = function ( e ) {

                    if ( ( _img.complete ) || ( _img.readyState == 'complete' && e.type == 'readystatechange' ) ) {

                        ++i
                                
                        if( i === $imgs.length ) {

                            _done();
                        }

                    }

                    else if ( _img.readyState === undefined ) { // dont for IE

                      // re-fire load event

                    }

                }; // _checki \\


                $( _img ).bind( 'load readystatechange', function( e ) {_checki( e )} )
                    _checki({type:'readystatechange'}); // bind to 'load' event...

            });

        } else _done();

    });

};

$(function(){

    if ( /\biPhone|iPod|iPad\b/.test( navigator.userAgent ) )
    	$( '#page' ).css({background: 'transparent url("../img/mobile-bg.png") repeat-x center'})

    window.$window = $( window )

    window.shadows = {
        blue: '0 -1px 1px #0B86C8, -.5px 0 1px #fff',
        grey: '0 1px 1px #fff, -.5px 0 1px #9BA0A3',
        active: '0 -1px 1px #777878, -.5px 0 1px #fff'
    }

	try {
		var flash = swfobject.getFlashPlayerVersion();
		if(flash.major == 0)
		{
			document.location.href = document.location.href+"&type=html";
		}
	} catch(e) {}


	if(!debug) {
		document.oncontextmenu=new Function("return false");
	}

    Cufon.replace( 'a.i1, a.i2, a.i3', {textShadow: shadows.blue} )
    Cufon.replace( 'a.i4, a.i5, a.i6', {textShadow: shadows.grey} )

    //$( window ).hashchange(function (e, newHash) {
    //    checkPage( newHash )
        //alert( newHash )
    //});


    $.hash.init('blank.html');
    if ( location.href.indexOf( '#' ) == -1 )
        location.replace( '#/' )

    var flashvars = {
    };
    var params = {
        menu: "false",
        scale: "noScale",
        allowFullscreen: "true",
        allowScriptAccess: "always",
        wmode: 'opaque',
        name: 'safeguard',
        id: 'safeguard'
    };
    var attributes = {
        id:"safeguard"
    };

    swfobject.embedSWF("/swf/safeguard.swf", "flash", "980", "610", "9.0.0", '/swf/expressInstall.swf', flashvars, params, attributes)

    preloadImages()

})

function preloadImages() {

    window.$images = $( 'img' )
    window.images = {total: $images.length, loaded: 0}
    $progress = $( '#progress' )
    $progressBar = $progress.find( 'div' )
    
    images.total = ( swfobject.hasFlashPlayerVersion( '1' ) ) ? images.total + 1 : images.total
    images.total = ( $.browser.opera ) ? images.total -1 : images.total
    
    log( images.total )

    var width = {
            window: $window.width(),
            block: $progress.width()
        },
        height = {
            window: $window.height(),
            block: $progress.height()
        },
        top = Math.max( height.window - 34 - height.block, 0 ) / 2, // 34 is height of footer
        left = Math.max( width.window - width.block, 0 ) / 2

    $progress.css({left: left, top: top}).fadeIn( 500 )

    freeze( true )

    //$images.load( preloader )

    //setTimeout( function () {
    //    $( 'img' ).onImagesLoaded( function(){ /*$progress.fadeOut( 200 ); viewPage()*/ log( 'onImagesLoaded' ) } )
    //     $( 'img' ).each( function () { var oldsrc = this.src; this.src = '#'; this.src = oldsrc } );
    $( 'img' ).each( function () {
        $( this )
            .attr( 'oldsrc', this.src )
            .removeAttr( 'src' )
            .load( function () {
		        var w = this.width;
		        var h = this.height;
		        $( this.parentNode ).append(this);
                preloader()
            } )
            .error( function () {
                log( 'not loaded'+this.src )
            } )
            .attr( 'src', $( this ).attr( 'oldsrc' ) )
    } )
    //}, 3000 )
    
    viewPage( 'preload' )

}

function preloader () {
        ++images.loaded
        $progressBar.css( {width: Math.round( images.loaded / images.total * 100 ) + '%'} )
        if ( images.total == images.loaded + 1 ) {
            preloader.timeout = setTimeout( function(){$progress.fadeOut( 200 );viewPage();$( 'body' ).css( 'overflow', 'auto' )}, 10000 )
        }
        if ( images.total == images.loaded ) {
            clearTimeout( preloader.timeout )
            setTimeout( function(){$progress.fadeOut( 200 );viewPage();$( 'body' ).css( 'overflow', 'auto' )}, 200 )
        }
}

function viewPage ( preload ) {

    if ( preload ) {

	    window.$centerer = $( '#centerer' )

        $window.resize( position )
        
        setTimeout( function () {
            position.set( 'firstTime' )
            $centerer.fadeIn( 0 );
        }, 0 )

    	return
    }
    
    if ( ! $( '#hider' ).is( ':visible' ) ) return
    window.$centerer = $( '#centerer' )
    $( '#page' ).css( 'opacity', 1 )
    $( '#hider' ).fadeOut( 700 )
    $(window).resize( position )
    setTimeout( function () {
        position.set( 'firstTime' )
        $centerer.fadeIn( 0 );
        $( '#footer' ).animate( {bottom: 0}, 700 )
    }, 150 )
    freeze( false )
}

function position () {

    if ( position.timeout ) {
        clearTimeout( position.timeout )
    }

    position.timeout = setTimeout( position.set, 150 )

}

position.set = function ( firstTime ) {

    var width = {
            window: $window.width(),
            block: $centerer.width()
        },
        height = {
            window: $window.height(),
            block: 610//$centerer.height()
        },
        top = Math.max( height.window - 34 - height.block, 0 ) / 3, // 34 is height of footer
        left = Math.max( width.window - width.block, 0 ) / 2
    $( 'body' ).stop()
    $( 'body' ).animate( {backgroundPosition: ( left - 820 ) + 'px ' + ( top - 565 ) + 'px'}, ( firstTime ) ? 0 : 500 )
    //$( 'body' ).animate( {'background-position-x': ( left - 820 ) + 'px', 'background-position-y': ( top - 565 ) + 'px'}, ( firstTime ) ? 0 : 500 )
    $centerer.animate( {'padding-top': top, 'margin-left': left}, ( firstTime ) ? 0 : 500 )
}

function switchPage ( pageName ) {
    if ( $( 'body' ).hasClass( 'freeze' ) ) return false
    var link = ( ( pageName ) ? $( 'a[href=#' + pageName + ']' )[0] : this ) || this
    activateItem.apply( link )
    setPage( link.href.substring( link.href.indexOf( '#' ) + 1 ) )
    return false
}

function activateItem () {
    var $oldActive = $( '.active' ).removeClass( 'active' ),
        $current = $( this ).addClass( 'active' )
    if ( $current[0].nodeType && $current.parent()[0].tagName == 'h1' ) return
    if ( $oldActive.length ) {
        var shadow = ( $oldActive.hasClass( 'i1' ) || $oldActive.hasClass( 'i2' ) || $oldActive.hasClass( 'i3' ) ) ? 'blue' : 'grey' 
        if( $oldActive.parents( '#header' ).length )
            Cufon.replace( $oldActive, {textShadow: shadows[ shadow ]} )
    }
    if( $current.parents( '#header' ).length )
        Cufon.replace( $current, {textShadow: shadows.active, color: '#fff'} )
}

function setPage ( url ) {
    log( 'setPage' )
    navigate( url )
    try {document.safeguard.navigate( url )}
    catch ( error ) {log( error )}
}

function navigate ( url ) {
    log( 'navigate' )
    setTitle( url )
    $.hash.go( url )
    freeze( true )
}

function flashReady ( error ) {
    log( 'flashReady' )
    if ( error ) {
        log( error )
        return
    }

    $( '#header a, a.hashlink' ).each( function () {
        this.hashlink = this.href.substring( this.href.indexOf( '#' ) + 1 )
    } ).click( switchPage )

    setInterval( function () {checkPage()}, 550 )

    freeze( false )

}

function flashBackgroundRendered () {
    
	log( 'flashBackgroundRendered' )
	preloader()
	$( '#safeguard' ).height( '610' )
}

function pageReady ( pageId, error ) {
    log( 'pageReady' )
    if ( error ) {
        log( 'pageReady: ' + error )
        return
    }
    freeze( false )
}

function checkPage ( currentPage ) {
    var activeItem = $( 'a.active' )
    currentPage = currentPage || location.href.substring( location.href.indexOf( '#' ) + 1 )
    if ( currentPage && ! activeItem.length ) {
        switchPage( currentPage )
        return
    }
    if ( ! activeItem.length )
        return
    activeItem = activeItem[0].href
    activeItem = activeItem.substring( activeItem.indexOf( '#' ) + 1 )
    if ( currentPage != activeItem ) {
        switchPage( currentPage )
    }
}

/*
function checkPage (  ) {
    var currentPage = location.href.substring( location.href.indexOf( '#' ) + 1 ),
        activeItem = $( 'a.active' )
    if ( currentPage && ! activeItem.length ) {
        switchPage( currentPage )
    }
    if ( ! activeItem.length )
        return
    activeItem = activeItem[0].href
    activeItem = activeItem.substring( activeItem.indexOf( '#' ) + 1 )
    if ( currentPage != activeItem ) {
        switchPage( currentPage )
    }
}
*/

function freeze ( turnOn ) {
    $( 'body' )[ ( turnOn ) ? 'addClass' : 'removeClass' ]( 'freeze' )
}

function setTitle ( id ) {
    document.title = ( pages[ id ] ) ? 'Safeguard — ' + pages[ id ] : 'Safeguard'
    if ( !pages[ id ] )
        log( id )
}

var pages = {
    '/':                  'Добро пожаловать',
    '/guest_room':        'Гостиная комната',
    '/kids_playground':   'Детская площадка',
    '/kitchen':           'Кухня',
    '/safeguard':         'О Safeguard',
    '/pediatrician_tips': 'Беседа с педиатром',
    '/handwash_guides':   'Мытьё рук для детей',
    '/share':             'Порекомендовать другу'
}

function log ( message ) {
    if ( window.console && window.debug )
        console.log( message )
}

