/*
 * 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() {
	  var ul = this;
    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) $(ul).slideDown('fast');
          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);
    $('#recipe_suggestions').addClass('processed');
}


function recipeCreateTabs() {
    $('#recipe_suggestions ul.nav li a').click(function(){recipeActivateTab(this)});
}

function recipeActivateTab(a, first) {
    // default tab
	
    var id = 'recipes_dag';
    // get tab (clicked or trough hash)
    var url = first ? document.location.href : a.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').removeClass('active_tab');


    if ($('#'+id).size()) {
    	$('#'+id).addClass('active_tab');
        if ($('#tab_'+tab)) $('#tab_'+tab).addClass('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_recipeID, daily_recipe){
        var str='';
        str+='<ul>';
        var recipe_cards = $('#' + daily_recipe.id + ' .recipe_card');
        recipe_cards.each(function(recipe_cardID, recipe_card){
        	// convert date tot dutch text
        	var recipe_card = $(recipe_card);
        	if (!recipe_card.find('p.image img').size()) return;
            if (recipe_cardID==0) recipe_card.addClass('recipe_active');
            recipe_card[0].id=daily_recipe.id+'_'+recipe_cardID;
            if (daily_recipe.id == 'recipes_dag') replaceTitle(recipe_card.find('h3.recipe_date')[0]);
            str+='<li'+ ((recipe_cardID==0)?' class="first recipe_active"':'')+'>';
            str+='<span class="arrow"></span>';
            str+='<a href="#_'+recipe_card[0].id+'">';
            if (daily_recipe.id=='recipes_bonus') str+='<img src="'+recipe_card.find('.bonus_product p.product_image img')[0].src+'" alt="'+recipe_card.find('.bonus_product h5')[0].innerHTML+'"/>';
            else str+='<img src="'+recipe_card.find('p.image img')[0].src+'" alt="'+recipe_card.find('h4 a')[0].innerHTML+'"/>';
            str+='</a>';
            if (daily_recipe.id=='recipes_dag') {
            	str+='<span>'+recipe_card.find('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).prepend(recipes_thumbnailDiv);
        str=null;
    });
    // click event on link
    $('#recipe_suggestions div.recipes_thumbnail a').click(function(){recipeClickThumbnail(this);});

    $('#recipe_suggestions div.recipes_thumbnail a img').each(function(i,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(a) {
    var url = a.href;
    var id = url.substr(url.lastIndexOf('#_') + 2);
    // remove all active classes

    var parent_id = $(a).parents('div.active_tab').attr('id');
    $('#recipe_suggestions #'+parent_id+' .recipe_active').removeClass('recipe_active');
  
    // show active recipe
    
    $('#'+id).addClass('recipe_active');
   

    // actviate li
    $(a.parentNode).addClass('recipe_active');

}

function recipeShowAltText() {
    var altDiv = document.createElement('div');
    altDiv.innerHTML = this.improvedAlt;
    altDiv.id='recipe_thumbnail_alt';
    altDiv.className = 'altdiv_' + $(this).parents('div:eq(1)').attr('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).bind('mousemove', recipeAltFollowMouse);

}
function recipeHideAltText() {

    $(this).unbind('mousemove', recipeAltFollowMouse);
    // remove the improved alt block
    $('#recipe_thumbnail_alt').remove();

}

function recipeAltFollowMouse(event) {
	
	
    $('#recipe_thumbnail_alt')[0].style.left = event.pageX-15+'px';
    $('#recipe_thumbnail_alt')[0].style.top = event.pageY-25+'px';
}



function recipesCreateFoundList() {

	$('#recipes_found_container').wrap('<div id="recipes_found_container_outer" />');
	
   
    $('#recipes_found_nav li a').live('click',function(){
    	$('body').addClass('waiting');
    	var link = this;
        $('#recipes_found_container_outer').load(link.href+' #recipes_found_container',function(){
        	$('body').removeClass('waiting');
        });
    	
        return false;
    });
}







/* }}} */
/* 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).bind('mouseover',function(){
                $('#rating_feedback').html('U hebt al gestemd');
            });
            $(votedspan).bind('mouseout',function(){
                $('#rating_feedback').html('Waardering');
            });
        }
    }
    voted();

    $('#recipe_info .recipe_rating span span').each(function(aID, a) {
        // 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).addClass('stars_' + this.position);
            $('#rating_feedback').html('Geef uw beoordeling: ' + this.position + ((this.position==1)?' ster':' sterren'));

        }

        function on_mouse_out(ev) {
            $(this.parentNode).removeClass('stars_' + this.position);
            $('#rating_feedback').html('&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) {
        	
	       

        }

        /**
         * 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.size() == 0 ) {
                return;
            }
            rbutton[0].checked = 'checked';
            var request = $.ajax({
            		url: '/recepten/raterecept',
                    type: 'POST',
                    data: $('#rate_form').serialize(),
                    complete: function (XMLHttpRequest, textStatus) {
                        var headerJSON = XMLHttpRequest.getResponseHeader('X-JSON');
                        if (headerJSON == null) {
		                     throw 'Missing JSON data in response header.';
		                 }
                        headerJSON = eval('(' + headerJSON + ')');
                        $('#rating_feedback').html('Bedankt voor uw beoordeling');
		                 
		                 $('#recipe_rating_number').html(parseInt(headerJSON.noOfRates));
		                 
		                 initbox.className = 'recipe_rating_stars initstars_'
		                                     + parseInt(headerJSON.newrate);
		                 initbox.innerHTML = parseInt(headerJSON.newrate)
		                     + ((headerJSON.newrate == 1) ? ' ster' : ' sterren');
		                 initbox.id = 'recipe_rating_voted';
                        
                    },

         
                    failure: on_rating_failure
                });

            return false;
        }

        $(a).bind('mouseover', on_mouse_over);
        $(a).bind('mouseout', on_mouse_out);
        $(a).bind('click', on_post_rating);
    });
}

/* }}} */
/* Recipe search autocomplete {{{ */

function recipeAjaxSearcher() {
    $('form input.autocompleter').each(
        function(i, inputComplete) {
        	var inputComplete = $(inputComplete);
            if (inputComplete.attr('data-url')) {

                var default_text;

                inputComplete.bind('focus', function(ev) {
                    if (inputComplete[0].value.indexOf('Vul een ingredi') == 0) {
                        default_text = inputComplete[0].value;
                        inputComplete[0].value = '';
                    }
                    this.select();
                });

                // reset the text to the original, instructive text:
                inputComplete.bind('blur', function (ev) {
                    if (inputComplete[0].value == '' && default_text != undefined) {
                        inputComplete[0].value = default_text;
                    }
                });
                
                
                var dataUrl = inputComplete.attr('data-url');
                var dataForm = inputComplete.parents('form:first');
                
                               
                $(inputComplete).autocomplete({
                	search: function(){
                		var searcher = this;
                		if ($(searcher).autocomplete('widget').parent('body').size()==0) $('body').append($(searcher).autocomplete('widget'));
                		$(searcher).autocomplete('widget').css({zIndex: '10000'}).width(searcher.offsetWidth - 1);
                		if (ua.ie6) $('select').css({visibility: 'hidden'});
                	},
                	close: function(){
                		if (ua.ie6) $('select').css({visibility: 'visible'});
                	},
                	source: function(request, response) {
                		
                		$.ajax({
	    					url: dataUrl,
	    					type: 'POST',
	    					data: inputComplete.serialize(),
	    					success: function(data) {
	    						var results = new Array();
	    						$(document.createElement('div')).html(data).find('li').each(function(){results.push($(this).text());});
	    						response(results);
	    						
	    					}
	    				});
                	}
                	
            	});
                
                $(inputComplete).autocomplete('widget').css({width: (inputComplete.width()+10)+'px'});
               
            }
    });
}

/* }}} */
/* 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') {
                self.show_movie(ev);
                if (controller) controller.addClass('playing');
            } else {
                self.hide_movie(ev);
                if (controller) controller.removeClass('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).bind('click', self.toggle_movie);
            player[0].appendChild(cb);
            

            player[0].style.display = 'block';
            state = 'opened';
        }

        self.hide_movie = function(ev) {
            var player = $('#recipe_instruction_video_player');
            player[0].style.display = 'none';
            player[0].innerHTML = '';
            state = 'closed';
        }

        function _init_url(placeholder) {
            var url = $(placeholder).find('a:first').attr('href');
            if (url === null) {
                throw 'Missing href in instruction video tag.';
            }
            return url;
        }

        function _create_control(placeholder) {

            var d = $(document.createElement('span'));
            d.addClass('recipe_instruction_video_control');
            d[0].innerHTML = '<a id="recipe_movie_controller" href="#recipe_instruction_video_player">play</a>';
            d.find(':first').bind(
                    'click', self.toggle_movie);
            placeholder.append(d);

            var c =$(document.createElement('div'));
            c.attr('id', 'recipe_instruction_video_player');
            $('#recipe_info').append(c);

            return d;
        }

        // run:
        self.init(placeholder);
        return self;
    }

    var placeholder = $('#recipe_instruction_video');
    if ( ! placeholder.size()) { // test'n'skip
        return;
    }

    // check for flash version
    if (deconcept.SWFObjectUtil.getPlayerVersion().major >= 8) {
    	InstructionVideoController({}, placeholder);
    }
}

/* }}} */

/*
  DOM enhancements only applicable for recipepages
*/




/* Social Sharing. */

function shareRecipe(){

	if ($('li.share .tipcontent > div').size()) {
		
		var tipContent = $('li.share .tipcontent > div:first');
		
		$('li.share > a').attr('title','').live('mouseover',function(){
			var a = $(this);
			var offset = a.offset();
			if (!ua.ie6) $(this).tipBox({content: tipContent, persist: true, tiplocation: 'left', cssClass: 'shareTip'});
			else {
				$('<div class="shareTip"/>').css({
					position: 'absolute',
					left: offset.left-96,
					top: offset.top-80,
					width: 200,
					backgroundColor: '#fff',
					padding: '5px',
					border: '1px solid #333'
					
				}).html(tipContent.html()).appendTo('body');
			}
		});
		
		$('.shareTip').live('mouseleave click',function(){
			if ($.support.opacity) {
				$(this).fadeTo(200,0,function(){
					$(this).remove();
				})
			}
			else {
				$(this).remove();
			}
		});
	}
	
	if (!$('.share-options a').size()) return;
	$('.share-options a').live('click',function(){
		sitestatTellerPage('recepten.recept.'+this.className);
		var w = 600;
		var h = 500;
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
		window.open(this.href, null,'menubar=0,resizable=1,width='+w+',height='+h
				+',left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=1,toolbar=0,directories=0,scrollbars=1');

		return false;
	});	
}


function recipesVED(){
	if (!$('#recipes_ved').size()) return;
	var i = 5;
	var animationSpeed = 1400;
	var ved = $('#recipes_ved');
	var recipes = $('ul.recipes', ved);
	var marginRight;
	recipes.find('li').each(function(i){
		$(this).attr('data-index',(i+1));
	});
	
	var recipesSize = recipes.find('li').size();
	var ghosts = recipesSize%i>0?(i-recipesSize%i):0;
	
	$(window).resize(function(){
		marginRight = (($('div.recipes',ved).width()-(i*$('div.recipes img:first',ved).outerWidth()))/(i-1));
		recipes.find('li').css({marginRight: marginRight});	
	}).resize();
	
	for (var k=0; k<ghosts; k++) {
		recipes.append('<li class="ghost" data-index="'+recipesSize+'"><span>&nbsp;</span></li>');
	}
	
	
	function updateIndex(){
		
		var currentStartIndex = recipes.find('li:first').attr('data-index');
		var currentEndIndex = recipes.find('li:eq('+(i-1)+')').attr('data-index');
		$('div.nav p span',ved).html(currentStartIndex + '-' + currentEndIndex + ' van ' + recipesSize);
	}
	
	$('div.nav p',ved).prepend('<span/>&nbsp;|&nbsp;');
	updateIndex();
	
	
	$('.nav a').click(function(){
		var a = $(this);
		switch (true) {
		case a.hasClass('prev'):
			if (!a.hasClass('disabled')) {
				a.addClass('disabled');
				$('li:gt('+(recipes.find('li').size()-(i+1))+')',recipes).prependTo(recipes);
				recipes.css({left: (0-($('div.recipes',ved).width()+marginRight))});
				
				$('ul.recipes',ved).stop().animate({left: 0},{
					duration: animationSpeed, 
					easingMethod: function(t, b, c, d) {
						return -c*t*t/(d*d) + 2*c*t/d + b;
					},
					complete: function(){
						a.removeClass('disabled');
						
						updateIndex();
					}
				});
			}
			return false;
			break;
		case a.hasClass('next'):
			if (!a.hasClass('disabled')) {
				a.addClass('disabled');
				
				
				
				
				$('ul.recipes',ved).stop().animate({left: (0-($('div.recipes',ved).width()+marginRight))},{
					duration: animationSpeed, 
					easingMethod: function(t, b, c, d) {
						return -c*t*t/(d*d) + 2*c*t/d + b;
					},
					complete: function(){
						a.removeClass('disabled');

						recipes.find('li:lt('+i+')').appendTo(recipes);
						recipes.css({left: 0});
						updateIndex();
					}
				});
			}
			return false;
			break;
		
		
		
		}
		
	});
	
	recipes.find('a').click(function(){
		var a = $(this);
		var href = a.attr('href');
		if (href) {
			var matches = href.match(/id=([0-9]+)/);
			if (matches && matches[1]) {
				var recipeID = matches[1];
				$.ajax({
					url: '/data/for_every_day/detail?id='+recipeID,
					success: function(data){
						$('.detail', ved).html(data);
					}
				});
				return false;
			}
		}
	});
	
	recipes.find('img').hover(function(e){
		var title = $(this).attr('data-alt');
		$('#alt-alt').remove();
		if (title && title!='') {
			$('<div id="alt-alt"><span/>'+title+'</div>').appendTo('body');
		}
	},function(){
		$('#alt-alt').remove();
	}).each(function(){
		$(this).attr('data-alt',$(this).attr('alt')).attr('alt','');
	});
	
	
	$(document).mousemove(function(e){
		$('#alt-alt').css({left: e.pageX, top: e.pageY});
	});
	if (!ua.ie6) {
		if (!getCookie('ved-first')) {
			
					
			$('#recipes_ved h2 span').tipBox({
				cssClass: 'ved-tipbox stay-alive', 
				tiplocation: 'right', 
				content: 'Nu met elke maand de nieuwste recepten. <a href="#_close" class="close">sluiten</a>', 
				arrow: 'left', 
				persist: true});
			
			$('.ved-tipbox, .ved-tipbox a.close').live('click', function(){
				$('.ved-tipbox').remove();
				setCookie('ved-first',new Date(),'364');
				return false;
			});
		}
	}
	
	
}

if (loader) {
	loader.schedule("recipeAjaxSearcher autocomplete", recipeAjaxSearcher);
	loader.schedule("setupRefinement", setupRefinement);
	loader.schedule("recipesAttachRatingFunctions", recipesAttachRatingFunctions);
	loader.schedule("recipeInitRecipeSuggestions", recipeInitRecipeSuggestions);
	loader.schedule("recipeInitVED", recipesVED);
	loader.schedule("recipesCreateFoundList", recipesCreateFoundList);
	loader.schedule("recipesInstructionVideo", recipesInstructionVideo);
	loader.schedule("init share", shareRecipe);
}

// vim: fdm=marker ts=4 sts=4 sw=4 noet

