// Site wide wide events and actions.
window.addEvent('domready', function(){
    // Init the window
    resizeEvent();

    // Set up browser size detection and hook events
    window.addEvent('resize', function(){
            resizeEvent();
        }
    );

    addDefaulterField('.fncEmailField', 'email address');
    addDefaulterField('.fncPostcodeInput', 'postcode / town / city');

    initWhereToBuyNav();
    
    initRecipesNav();
    
		$$('.rate').each(function(element,i){
		element.addEvent('click', function(e){
			var myStyles = ['nostar', 'onestar', 'twostar', 'threestar', 'fourstar', 'fivestar', 'sixstar', 'sevenstar', 'eightstar', 'ninestar', 'tenstar'];
			myStyles.each(function(myStyle){
				if(element.getParent().hasClass(myStyle)){
					element.getParent().removeClass(myStyle)
				}
			e.preventDefault();
			});	
			
			myStyles.each(function(myStyle, index){
				if(index == element.id){
					element.getParent().toggleClass(myStyle);
					var anchor = $(element.id).getFirst('a');
					var req = new Request({
						method:'post',
						url: '/ratings/save/',
						data: {'rating' : element.id, 'recipe_id' : element.getParent().id},
						//onRequest: function(){ //alert('Request made. Please wait...');},
						onComplete:function(response){window.location.reload(true)}
					}).send();
					//alert('Clicked '+element.id);
					//alert(anchor.href);
				}
			});		
			
		});
	});
	
	/* hide using opacity on page load */
		var fb_modal = $('fb-modal');
		if(fb_modal) {
			$('fb-modal').setStyles({
				opacity:0,
				display:'block'
			});
			/* hiders */
			$('fb-close').addEvent('click',function(e) { $('fb-modal').fade('out'); });
			window.addEvent('keypress',function(e) { if(e.key == 'esc') { $('fb-modal').fade('out'); } });
			$(document.body).addEvent('click',function(e) { 
				if($('fb-modal').get('opacity') == 1 && !e.target.getParent('.generic_dialog')) { 
					$('fb-modal').fade('out'); 
				} 
			});
			/* click to show */ 
			$('fb-trigger').addEvent('click',function(e) {
				$('fb-modal').fade('in');
				e.preventDefault();
			});
			
			$('submit').addEvent('click',function(e) { 
				$('comments').send();
				$('fb-modal').fade('out'); 
				e.preventDefault();
			});
		}
		
		
		var comments_modal = $('comments-modal');
		if(comments_modal) {
			$('comments-modal').setStyles({
				opacity:0,
				display:'block'
			});
			/* hiders */
			$('comments-close').addEvent('click',function(e) { $('comments-modal').fade('out'); });
			window.addEvent('keypress',function(e) { if(e.key == 'esc') { $('comments-modal').fade('out'); } });
			$(document.body).addEvent('click',function(e) { 
				if($('comments-modal').get('opacity') == 1 && !e.target.getParent('.generic_dialog')) { 
					$('comments-modal').fade('out'); 
				} 
			});
			/* click to show */ 
			$('comments-trigger').addEvent('click',function(e) {
				$('comments-modal').fade('in');
				e.preventDefault();
			});
			
		}
});



function initScrollToOnDomReady(elemSelector){
    window.addEvent('domready', function(){	
		if(!$$(elemSelector)[0]) return;	
		  var scrollFx = new Fx.Scroll(window).toElement($$(elemSelector)[0]);
        }
    );
}


// Pop Up - added dynamically in IndexController.php

function setupPromoPopup(){
	window.addEvent('domready', function(){
	
		if(!$$('#promoPopUp')[0]) return;
		if(!$$('a.close')[0]) return;
		
			var myFx = new Fx.Tween('promoPopUp', {
				property: 'opacity',
				duration: 1500,
				transition: Fx.Transitions.Quart.easeInOut
			});
			
			myFx.start(0, 1);

			$$('a.close')[0].addEvent('click', function(e){
				
				e.preventDefault();
				var myFx = new Fx.Tween('promoPopUp', {
					property: 'opacity',
					duration: 1000, 
					transition: Fx.Transitions.Quart.easeInOut
				});
				myFx.start(1,0);
			});
	});
}


//
function initWhereToBuyNav(){

    // Prevent if is buy page...
    if($$('body')[0].hasClass('buy')) return;
    
    /*  Where to buy nav action */
    var wbCont = $$('.whereToBuy')[0];
    var wbHit = $$('.fncBuyHit')[0];
    var wbForm = $$('.whereToBuy form')[0];
    if(wbForm){
        var wbInp = wbForm.getElements('input.fncPostcodeInput')[0];
    }

    // buy fncBuyHit here on
    // buy fncBuyHit here

    if(!wbCont || !wbHit || !wbForm || !wbInp) return;

        // Set initial states for consistency
    wbCont.setStyle('opacity', 0);
    wbForm.setStyle('top', '-40px');

    // Initial state
    wbHit.store('is_in', false);
    wbHit.store('is_moving', false);

    /* Set up transitions to be used */
    var fxContIn = new Fx.Tween(wbCont, {
        duration: 500,
        transition: Fx.Transitions.Pow.easeIn
        }
    );

    var fxContOut = new Fx.Tween(wbCont, {
        duration: 500,
        transition: Fx.Transitions.Pow.easeOut
        }
    );

    var fxFormIn = new Fx.Tween(wbForm, {
        duration: 500,
        transition: Fx.Transitions.Pow.easeOut
        }
    );

    var fxFormOut = new Fx.Tween(wbForm, {
        duration: 500,
        transition: Fx.Transitions.Pow.easeIn
        }
    );

    //
    wbHit.addEvent('mouseenter', function(){

        var isIn = wbHit.retrieve('is_in');

        // no need to do nuffink.
        if(isIn) return;

        // set new states...
        wbHit.store('is_in', true);
        wbHit.store('is_moving', true);

        // set up styles [to show the basket appopriately]
        setLiStyles(wbHit, true);

        fxContIn.start('opacity', 0, 100).chain(function(){
            fxFormIn.start('top', '-40px', '0').chain(function(){
                wbHit.store('is_moving', false);
            });
        });
    });

    //
    var formOutEvent = function(){

        var isIn = wbHit.retrieve('is_in');

        // no need to do nuffink.
        if(!isIn) return;
        if(wbHit.retrieve('is_moving')) return;

        if(wbInp.retrieve('defValue') == wbInp.get('value')){

            // set new states...
            wbHit.store('is_in', false);
            wbHit.store('is_moving', true);

            // set up styles [to show the basket appopriately]
            setLiStyles(wbHit, false);

            fxFormOut.start('top', 0, -40).chain(function(){
                fxContOut.start('opacity', 100, 0).chain(function(){
                    wbHit.store('is_moving', false);
                });
            });

        }
    }

    // To show the basket appopriately.
    function setLiStyles(li, toOn){
        if(!li.hasClass('here')){
            if(toOn){
                li.addClass('on');
            } else {
                li.removeClass('on');
            }
        }
    }

    // Apply the styles...
    wbHit.addEvent('mouseleave', formOutEvent);
    wbHit.addEvent('blur', formOutEvent);    
}


// Action the height of the window and make fixed height if below that height.
function resizeEvent(){
    // console.log('Resize process called');

    var bodyEl = $$('body')[0];
    var wrapEl = $('fncWrap');
    var ftrEl = $$('.blockFooter')[0];

    if(!wrapEl || !bodyEl || !ftrEl) return;

    // OK - all valid do proceed
    var h = window.getHeight();
    var minHeight = 600;
    var isHome = bodyEl.hasClass('home');

    // 
    if(h < minHeight){

        if(isHome){
            wrapEl.set('class', 'wrap fixHome');
        } else {
            wrapEl.set('class', 'wrap fixContent');
        }

    } else {

        wrapEl.set('class', 'wrap');
        
    }
}

//RECIPES DROPOUT
function initRecipesNav(){

    /*  Recipes nav action */
    var recipesCont = $$('.recipesNavList')[0];
    var recipesHit = $$('.fncRecipesHit')[0];
    var recipesList = $$('.recipesNavList ul')[0];

    // buy fncBuyHit here on
    // buy fncBuyHit here

    if(!recipesCont || !recipesHit || !recipesList) return;

        // Set initial states for consistency
    recipesCont.setStyle('opacity', 0);
    recipesList.setStyle('top', '-40px');

    // Initial state
    recipesHit.store('is_in', false);
    recipesHit.store('is_moving', false);

    /* Set up transitions to be used */
    var fxContIn = new Fx.Tween(recipesCont, {
        duration: 300,
        transition: Fx.Transitions.Pow.easeIn
        }
    );

    var fxContOut = new Fx.Tween(recipesCont, {
        duration: 200,
        transition: Fx.Transitions.Pow.easeOut
        }
    );    
    
    var fxFormIn = new Fx.Tween(recipesList, {
        duration: 300,
        transition: Fx.Transitions.Pow.easeOut
        }
    );

    var fxFormOut = new Fx.Tween(recipesList , {
        duration: 200,
        transition: Fx.Transitions.Pow.easeIn
        }
    );

    //
    recipesHit.addEvent('mouseenter', function(){

        var isIn = recipesHit.retrieve('is_in');

        // no need to do nuffink.
        if(isIn) return;

        // set new states...
        recipesHit.store('is_in', true);
        recipesHit.store('is_moving', true);

        
        // set up styles [to show the basket appopriately]
        setLiStyles(recipesHit, true);

        fxContIn.start('opacity', 0, 100).chain(function(){
            fxFormIn.start('top', '-40px', '0').chain(function(){
                recipesHit.store('is_moving', false);
            });
        });
    });

    //
    var formOutEvent = function(){

        var isIn = recipesHit.retrieve('is_in');

        // no need to do nuffink.
        if(!isIn) return;
        if(recipesHit.retrieve('is_moving')) return;

        

            // set new states...
            recipesHit.store('is_in', false);
            recipesHit.store('is_moving', true);

            // set up styles [to show the basket appopriately]
            setLiStyles(recipesHit, false);

            fxFormOut.start('top', 0, -40).chain(function(){
                fxContOut.start('opacity', 100, 0).chain(function(){
                    recipesHit.store('is_moving', false);
                });
            });

        
    }

    // To show the basket appopriately.
    function setLiStyles(li, toOn){
        if(!li.hasClass('here')){
            if(toOn){
                li.addClass('on');
            } else {
                li.removeClass('on');
            }
        }
    }

    // Apply the styles...
    recipesHit.addEvent('mouseleave', formOutEvent);
    recipesHit.addEvent('blur', formOutEvent);    
}




// --------------------
// SWF object 
// --------------------

// Logo
var flashvarsLogo = {
};
var paramsLogo = {
    play: 'true',
	loop: 'true',
	scale: 'showall',
	wmode: 'transparent',
	bgcolor: '#BBD0E7',
	menu: 'true',
	allowFullScreen: 'false',
	allowScriptAccess: 'sameDomain'
};
var attributesLogo = {
    id: '/x/swf/hp-logo-butterflies',
    name: '/x/swf/hp-logo-butterflies'
};

swfobject.embedSWF(
    "/x/swf/hp-logo-butterflies.swf",
    "flash-logo-butterflies",
    "290",
    "300",
    "7.0.0",
    "/x/swf/expressInstall.swf",
    flashvarsLogo,
    paramsLogo,
    attributesLogo
);


// Milk is life
var flashvarsMilk = {
};
var paramsMilk = {
    play: 'true',
	loop: 'true',
	scale: 'showall',
	wmode: 'transparent',
	bgcolor: '#BBD0E7',
	menu: 'true',
	allowFullScreen: 'false',
	allowScriptAccess: 'sameDomain'
};
var attributesMilk = {
    id: '/x/swf/milk-is-life',
    name: '/x/swf/milk-is-life'
};

swfobject.embedSWF(
    "/x/swf/milk-is-life.swf",
    "milk-is-life",
    "380",
    "210",
    "7.0.0",
    "/x/swf/expressInstall.swf",
    flashvarsMilk,
    paramsMilk,
    attributesMilk
);

/**
 * Shows elements when the grass is loaded. Must have equiv noscript.css for
 * things to be always visible if scripting disabled.
 */
window.addEvent('domready', function(){

    // Elements that have been hidden in CSS and will be revealed when grass
    // loads. Also see noscript in layout.
    var revealSelectors = [
        '.homeFlashContentWrap',
        '.mainContent',
        '.footerNav'
    ];
    
    var img = new Asset.image('/x/img/static/meadow.png', {

        onload: function(){

            var isIE6 = Browser.Engine.name == 'trident' && Browser.Engine.version <= 4;
            if(!isIE6){
                if($$('.blockFooter')[0]){
                    $$('.blockFooter')[0].setStyle(
                        'background', 'url(/x/img/static/meadow.png) repeat-x bottom left'
                    );
                }
            }             

            revealSelectors.each(function(sel, index){
                 var showElems = $$(sel);
                 
                 if(!showElems) return;
                 showElems.each(function(showElem){
                     showElem.setStyle('visibility', 'visible');
                 });
                }
            );
           
        }
        
    });

});

