/*
 * Recipe/food subsite javascript enhancements.
 *
 * Depends on default.js and other global scripts.
 *
 */

/* Recipe search result: Collapsing refinement of recipes {{{ */

function setupRefinement() {
  if (!$("refine")) return;
  var uls = $$("ul .expand");
  uls.each(function(ul) {
    if (ul.parentNode.id != "refine_extra") {
      var lis = ul.getElementsByTagName("li");
      var div = ul.parentNode;
      var a = div.appendChild(document.createElement("p")).appendChild(document.createElement("a"));
      a.appendChild(document.createTextNode("Meer"));
      a.className = "more";
      a.href = "#" + div.id;
      a.onclick = function() {
        if (this.showing) Effect.BlindDown(ul, {duration: 1});
          else ul.style.display = "none";
        this.firstChild.nodeValue = (this.showing) ? "Minder..." : "Meer...";
        this.className = (this.showing) ? "less" : "more";
        this.showing = !this.showing;
        return false;
      };
      a.onclick();
    }
  });
}

/* }}} */
/* Recipe subhome tab-browser for daily recipes {{{ */

function getX(obj){
   return( obj.offsetParent==null ? obj.offsetLeft : obj.offsetLeft+getX(obj.offsetParent) );
}

function getY(obj) {
   return( obj.offsetParent==null ? obj.offsetTop : obj.offsetTop+getY(obj.offsetParent) );
}


function recipeInitRecipeSuggestions() {
    recipeCreateTabs();
    recipeCreateThumbnails();
    recipeActivateTab(false,true);
    if ($('recipe_suggestions')) $('recipe_suggestions').addClassName('processed');
}


function recipeCreateTabs() {
    var recipes_categories = $$('#recipe_suggestions ul.nav li a');
    recipes_categories.each(function(recipeTab){
        recipeTab.onclick = recipeActivateTab;
    });
}

function recipeActivateTab(ev, first) {
    // default tab
    var id = 'recipes_dag';
    // get tab (clicked or trough hash)
    var url = first ? document.location.href : this.href;
    // get clicked tab (recipes_dag by default if no hash)
    if (url.lastIndexOf('#_')>0) id = url.substr(url.lastIndexOf('#_') + 2);

    var tab = id.replace('recipes_','');

    tab = tab.split('_')[0];
    id = 'recipes_' + tab;

    // remove all active_tabs classes
    $$('#recipe_suggestions .active_tab').each(function(activeTab){
        activeTab.removeClassName('active_tab');
    });


    if ($(id)) {
        $(id).addClassName('active_tab');
        if ($('tab_'+tab)) $('tab_'+tab).addClassName('active_tab');
    }
}



function recipeCreateThumbnails() {

    var daily_recipes = $$('#recipe_suggestions .daily_recipes');

    // Returns the Dutch day of the week for the given date object
	var getWeekdayString = function (d) {
		var weekdays = {
				0: 'zondag',
				1: 'maandag',
				2: 'dinsdag',
				3: 'woensdag',
				4: 'donderdag',
				5: 'vrijdag',
				6: 'zaterdag'
			};
		return weekdays[d.getDay()];
	}

	// Returns the Dutch name for the month of the given date object:
	var getMonthString = function (d) {
		var months = {
				0 : 'januari',
				1 : 'februari',
				2 : 'maart',
				3 : 'april',
				4 : 'mei',
				5 : 'juni',
				6 : 'juli',
				7 : 'augustus',
				8 : 'september',
				9 : 'oktober',
				10 : 'november',
				11 : 'december'
			};
		return months[d.getMonth()];
	}

	// Returns a Date obj from a datestring specified as DDMMYYYY:
	var getDate = function (date_string) {
		var d = parseInt(date_string.substring(0,2) - 0);
		var m = parseInt(date_string.substring(2,4) - 1); // 0-based
		var y = parseInt(date_string.substring(4,8) - 0);
		return new Date(y, m, d);
	}

	// Change unfortunate title from "05092008" to "Vrijdag 5 september 2008"
	var replaceTitle = function (titleElm) {
		if ( ! titleElm) {
			return;
		}
		var d = getDate(titleElm.innerHTML);
		titleElm.innerHTML = [
				getWeekdayString(d),
				d.getDate(),
				'<span>', getMonthString(d), '</span>'
			].join(' ');
	}


    daily_recipes.each(function(daily_recipe, daily_recipeID){
        var str='';
        str+='<ul>';
        var recipe_cards = $$('#' + daily_recipe.id + ' .recipe_card');
        recipe_cards.each(function(recipe_card, recipe_cardID){
        	// convert date tot dutch text
            if (recipe_cardID==0) recipe_card.addClassName('recipe_active');
            recipe_card.id=daily_recipe.id+'_'+recipe_cardID;
            if (daily_recipe.id == 'recipes_dag') replaceTitle(recipe_card.getElementsBySelector('h3.recipe_date')[0]);
            str+='<li'+ ((recipe_cardID==0)?' class="first recipe_active"':'')+'>';
            str+='<span class="arrow"></span>';
            str+='<a href="#_'+recipe_card.id+'">';
            if (daily_recipe.id=='recipes_bonus') str+='<img src="'+recipe_card.getElementsBySelector('.bonus_product p.product_image img')[0].src+'" alt="'+recipe_card.getElementsBySelector('.bonus_product h5')[0].innerHTML+'"/>';
            else str+='<img src="'+recipe_card.getElementsBySelector('p.image img')[0].src+'" alt="'+recipe_card.getElementsBySelector('h4 a')[0].innerHTML+'"/>';
            str+='</a>';
            if (daily_recipe.id=='recipes_dag') {
            	str+='<span>'+recipe_card.getElementsBySelector('p.thumbnail_text')[0].innerHTML+'</span>';
            }

            str+='</li>';


        });
        str+='</ul>';
        var recipes_thumbnailDiv = document.createElement('div');
        recipes_thumbnailDiv.className = 'recipes_thumbnail';
        recipes_thumbnailDiv.innerHTML=str;
        $(daily_recipe).insert({top: recipes_thumbnailDiv});
        str=null;
    });
    // click event on link
    $$('#recipe_suggestions div.recipes_thumbnail a').each(function(thumbnailLink){
        thumbnailLink.onclick=recipeClickThumbnail;
    });

    $$('#recipe_suggestions div.recipes_thumbnail a img').each(function(thumbnailLink){
        // use alt text for improved alt div
        thumbnailLink.improvedAlt = thumbnailLink.alt;
        thumbnailLink.alt = '';
        //  mouseover event on image
        thumbnailLink.onmouseover=recipeShowAltText;
        thumbnailLink.onmouseout=recipeHideAltText;
    });



}

function recipeClickThumbnail() {
    var url = this.href;
    var id = url.substr(url.lastIndexOf('#_') + 2);
    // remove all active classes
    var parent_id = $(this).up(3).id;
    $$('#recipe_suggestions #'+parent_id+' .recipe_active').each(function(activeRecipe){
        activeRecipe.removeClassName('recipe_active');
    });
    // show active recipe
    $(id).addClassName('recipe_active');
    /*
    if (parent_id=='recipes_bonus') {
    	var bonus_product = $(id).getElementsBySelector('div.bonus_product')[0];
    	if (bonus_product) {
    		if (bonus_product.getHeight()>30) {
    			bonus_product.addClassName('bonus_product_small');
    		}
    		else {
    			bonus_product.removeClassName('bonus_product_small');
    		}
    	}
    }
    */

    // actviate li
    $(this.parentNode).addClassName('recipe_active');

}

function recipeShowAltText() {
    var altDiv = document.createElement('div');
    altDiv.innerHTML = this.improvedAlt;
    altDiv.id='recipe_thumbnail_alt';
    altDiv.className = 'altdiv_' + $(this).up(4).id;
    // append it to the body (otherwise it wont go over the right part of the site)
    document.body.appendChild(altDiv);
    // follow the mouse
    this.observe('mousemove', recipeAltFollowMouse);

}
function recipeHideAltText() {

    this.stopObserving('mousemove', recipeAltFollowMouse);
    // remove the improved alt block
    if($('recipe_thumbnail_alt'))$('recipe_thumbnail_alt').remove();

}

function recipeAltFollowMouse(event) {
    $('recipe_thumbnail_alt').style.left = Event.pointerX(event)-15+'px';
    $('recipe_thumbnail_alt').style.top = Event.pointerY(event)-25+'px';
}



function recipesCreateFoundList() {


    function attachClickFunctions() {
        $$('#recipes_found_nav li a').each(function(navLink){
            $(navLink).observe('click',on_click_nav);
        });
    }

    function on_click_nav(ev) {
        $(document.body).addClassName('waiting');
        var request = new Ajax.Request($(this).readAttribute('href'), {
                    method: 'get',
                    onSuccess: on_load_succes,
                    onFailure: on_load_failure
                });
        Event.stop(ev);
        return false;
    }

    function on_load_succes(response) {
        // get the recipes_found html
        var pattern = /<div id="recipes_found_container" class="recipes_found">([\s\S]*?)<\/div>/;
        var matches = response.responseText.match(pattern);
        var new_results = matches[1];
        // place new html in container
        if (new_results) {
            $('recipes_found_container').innerHTML = new_results;
        }
        // re-attach events
        attachClickFunctions();
        // remove waiting status
        $(document.body).removeClassName('waiting');

    }
    function on_load_failure() {
        $(document.body).removeClassName('waiting');

    }




    attachClickFunctions();




}







/* }}} */
/* Recipe rating {{{ */


// Rate a recipe on a five-star scale:
function recipesAttachRatingFunctions() {


    // if voted, give feedback
    function voted() {
        var votedspan = $('recipe_rating_voted');
        if (votedspan) {
            $(votedspan).observe('mouseover',function(){
                var span = $('rating_feedback');
                if (span) span.innerHTML = 'U hebt al gestemd';
            });
            $(votedspan).observe('mouseout',function(){
                var span = $('rating_feedback');
                if (span) span.innerHTML = 'Waardering';
            });
        }
    }
    voted();

    $$('#recipe_info .recipe_rating span span').each(function(a, aID) {
        // Setup event handlers on the five stars:

        var ratingbox = a.parentNode.parentNode;
        var initbox = a.parentNode;
        var position = aID + 1;
        a.position = aID+1;

        function on_mouse_over(ev) {
            $(this.parentNode).addClassName('stars_' + this.position);
            var span = $('rating_feedback');
            if (span) span.innerHTML = 'Geef uw beoordeling: ' + this.position + ((this.position==1)?' ster':' sterren');

        }

        function on_mouse_out(ev) {
            $(this.parentNode).removeClassName('stars_' + this.position);
            var span = $('rating_feedback');
            if (span) span.innerHTML = '&nbsp;';
        }

        /**
         * Callback for successful rate post.
         *
         * The response is a working plain HTML for non-ajax browser;
         * The new data is stuck on the response as X-JSON as well.
         */
        function on_rating_success (response) {

            if (response.headerJSON == null) {
                throw 'Missing JSON data in response header.';
            }

            var span = $('rating_feedback');
            if (span) {
                span.innerHTML = 'Bedankt voor uw beoordeling';
            }
            span = $('recipe_rating_number');
            if (span) {
                span.innerHTML = new String(parseInt(response.headerJSON.noOfRates));
            }
            initbox.className = 'recipe_rating_stars initstars_'
                                + parseInt(response.headerJSON.newrate);
            initbox.innerHTML = parseInt(response.headerJSON.newrate)
                + ((response.headerJSON.newrate == 1) ? ' ster' : ' sterren');
            initbox.id = 'recipe_rating_voted';

        }

        /**
         * Callback for failed rate post.
         */
        function on_rating_failure (response) {
            initbox.className = 'recipe_rating_stars initstars_';
            // TODO better feedback.
        }

        /**
         * Post this rate
         */
        function on_post_rating (ev) {
            // Set form and run submit:
            var rbutton = $('rate_form_rate' + this.position);
            if ( ! rbutton ) {
                return;
            }
            rbutton.checked = 'checked';
            var request = new Ajax.Request('/recepten/raterecept', {
                    method: 'post',
                    parameters: $('rate_form').serialize(),
                    onSuccess: on_rating_success,
                    onFailure: on_rating_failure
                });

            Event.stop(ev);
            return false;
        }

        a.observe('mouseover', on_mouse_over);
        a.observe('mouseout', on_mouse_out);
        a.observe('click', on_post_rating);
    });
}

/* }}} */
/* Recipe search autocomplete {{{ */

function recipeAjaxSearcher() {
    $$('#primary form input.autocompleter,#secondary form input.autocompleter').each(
        function(inputComplete) {
            if (inputComplete.readAttribute('data-url')) {

                var default_text;

                inputComplete.observe('focus', function(ev) {
                    if (inputComplete.value.indexOf('Vul een ingredi') == 0) {
                        default_text = inputComplete.value;
                        inputComplete.value = '';
                    }
                    this.select();
                });

                // reset the text to the original, instructive text:
                inputComplete.observe('blur', function (ev) {
                    if (inputComplete.value == '' && default_text != undefined) {
                        inputComplete.value = default_text;
                    }
                });


                var div = new Element('div');
                div.id=inputComplete.id+'_auto_complete';
                div.className="autocompleter_container";
                $('main').insert(div); // outside to prevent positioning problems.
                new Ajax.Autocompleter(
                        inputComplete.id,
                        div.id,
                        inputComplete.readAttribute('data-url'),
                        {frequency: 0.1, minChars: 2}
                    );
            }
    });
}

/* }}} */
/* Create the recipe instruction video on a recipe detail page. {{{ */
function recipesInstructionVideo()
{

    function InstructionVideoController(self, placeholder) {

        // private members:
        var url;
        var state = 'closed';

        // initialize the controller. call this first.
        self.init = function (placeholder) {
            url = _init_url(placeholder);
            _create_control(placeholder);
        }

        // returns the URL for the movie
        self.get_url = function () { return url; }

        // show or hide the player:
        self.toggle_movie = function (ev) {
            var controller = $('recipe_movie_controller');
            if (state == 'closed') {
                this.show_movie(ev);
                if (controller) controller.addClassName('playing');
            } else {
                this.hide_movie(ev);
                if (controller) controller.removeClassName('playing');
            }
        }

        // show and play the movie:
        self.show_movie = function(ev) {
            var player = $('recipe_instruction_video_player');

            // create and play movie:
            var fo = new SWFObject(
                    '/_swf/videoplayer-v1.swf',
                    'recipe_instruction_video_movie',
                    '100%' /* width; 545px */,
                    '326' /* height */,
                    '8' /* Version 8 player */,
                    '#FFFFFF'
                );
            fo.addParam('quality', 'High');
            fo.addParam('menu', 'false');
            fo.addParam('allowScriptAccess', 'always');
            fo.addParam("wmode", "opaque");
            fo.addParam('flashvars', 'autoplay=true&theme=food&path=' + this.get_url());
            fo.write('recipe_instruction_video_player');

            // create close control;
            var cb = $(document.createElement('a'));
            cb.className = 'singular';
            cb.href = '#close_video';
            cb.innerHTML = 'video sluiten';
            cb.observe('click', self.toggle_movie.bindAsEventListener(self));
            player.appendChild(cb);

            player.style.display = 'block';
            state = 'opened';
        }

        self.hide_movie = function(ev) {
            var player = $('recipe_instruction_video_player');
            player.style.display = 'none';
            player.innerHTML = '';
            state = 'closed';
        }

        function _init_url(placeholder) {
            var url = placeholder.firstDescendant().readAttribute('href');
            if (url === null) {
                throw 'Missing href in instruction video tag.';
            }
            return url;
        }

        function _create_control(placeholder) {
            if (typeof showSWFObject === undefined) {
                throw 'Missing SWFObject library.';
            }

            var d = $(document.createElement('span'));
            d.addClassName('recipe_instruction_video_control');
            d.innerHTML = '<a id="recipe_movie_controller" href="#recipe_instruction_video_player">play</a>';
            d.firstDescendant().observe(
                    'click', self.toggle_movie.bindAsEventListener(self));
            placeholder.appendChild(d);

            var c =$(document.createElement('div'));
            c.setAttribute('id', 'recipe_instruction_video_player');
            $('recipe_info').appendChild(c);

            return d;
        }

        // run:
        self.init(placeholder);
        return self;
    }

    var placeholder = $('recipe_instruction_video');
    if ( ! placeholder) { // test'n'skip
        return;
    }

    // check for flash version
    if (deconcept.SWFObjectUtil.getPlayerVersion().major >= 8) {
        InstructionVideoController({}, placeholder);
    }
}

/* }}} */

/*
  DOM enhancements only applicable for recipepages
*/
if (loader) {
  loader.schedule("recipeAjaxSearcher autocomplete", recipeAjaxSearcher);
  loader.schedule("setupRefinement", setupRefinement);
  loader.schedule("recipesAttachRatingFunctions", recipesAttachRatingFunctions);
  loader.schedule("recipeInitRecipeSuggestions", recipeInitRecipeSuggestions);
  loader.schedule("recipesCreateFoundList", recipesCreateFoundList);
  loader.schedule("recipesInstructionVideo", recipesInstructionVideo);
}


// vim: fdm=marker ts=4 sts=4 sw=4 noet