$(document).ready(function(){

    recommendator = new Recommendator();

    //Login-boksin avaus ja sulkeminen
    $('#login_toggle_link').click(function(){
        $('div#login_form').toggle();
    });
    $('#login_toggle_link_close').click(function(){
        $('div#login_form').toggle();    
    });    
    //Kokkiscreen
    $('a#kokkiscreen_closed').click(function(){        
        //Ajax call
        $.get('/ajaxHandler.php', {kokkiscreen: true}, function(content){
            //Place data inside container
            $('div#kokkiscreen_open_content').empty();            
            $('div#kokkiscreen_open_content').append(content);
            //Slide up and down elements
            $('a#kokkiscreen_closed').slideUp();
            $('div#kokkiscreen_open').slideDown();                
        });        
    });
    $('div#kokkiscreen_open_footer a').click(function(){
        $('a#kokkiscreen_closed').slideDown();
        $('div#kokkiscreen_open').slideUp();
    });    
    //Headerin pikalinkit
    $('#header_quicklinks div.buttons a').click(function(){
        $('#header_quicklinks div.items_rest').slideToggle(300, function(){        
            $('#header_quicklinks div.buttons a').toggle();    
        });
    });
    //Keittiot-sivun tools-boksin avaus/sulkeminen
    $('div.net_kk_kitchen_tools a.header').click(function(){
        $('div.net_kk_kitchen_tools div.content').slideToggle(300, function(){        
        });
    });

    //Reseptinakyman tallenna keittokirjaan tools-boksin avaus/sulkeminen
    $("#recipes_view_addToCollection_open").click(function(){
        $('div#recipes_view_addToCollection').toggle();
    });
    $("#recipes_view_addToCollection_close").click(function(){
        $('div#recipes_view_addToCollection').toggle();    
    });   
    
    
	
    //Ostoslista    
    recount_dock_purchaselist();
    $("a#dock_purchaselist_toggle").click(function() {       
        reposition_dock_purchaselist(true);
    });    
    
    $("#dock_purchaselist ul li a").live("click", function() {    
        $.fancybox({
    		'href': $(this).attr('href'),
    		'transitionIn': 'fade',
    		'overlayOpacity': 0.7,
    		'overlayColor': '#000000' 
    	});
    	return false;
    });
		     

    //Suosituskone (loput js:t recommendator_documentready.tpl:ssa)
    $("a.recommendator_open_link").fancybox({
        'padding': 0,
		'transitionIn': 'fade',
		'overlayOpacity': 0.7,
		'overlayColor': '#000000' 
	});    
    //Goto Hate
    $("#recommendator_goto_hate").live("click",function() {
        $.get('/suosituskone/hate/', function(data) {
            $('#recommendator').fadeOut(function() {
                $('#recommendator').empty();
                $('#recommendator').html(data);
                $('#recommendator').fadeIn();                
            });
        });      
    });    
    
    //Goto Review
    var recommendator_goto_review_enabled = true;
    $("#recommendator_hate_beginreview").live("click",function() {
        if (recommendator_goto_review_enabled == true) {
            recommendator_goto_review_enabled = false;
            //Ajax loader        
            $("#recommendator_hate_beginreview").empty();
            $("#recommendator_hate_beginreview").html("<img src='/templates/layout_images/recommendator/ajax-loader.gif' style='margin: 12px 0 0 0;' alt='' />");    
            $.get('/suosituskone/review/', function(data) {
                $('#recommendator').fadeOut(function() {
                    $('#recommendator').empty();
                    $('#recommendator').html(data);
                    $('#recommendator').fadeIn();
                    recommendator_goto_review_enabled = true;                
                });
            });
        }
    });    
    
    //Goto Recommend
    var recommendator_goto_recommend_enabled = true;
    $("#recommendator_goto_recommend").live("click",function() {
        if (recommendator_goto_recommend_enabled == true) {
            recommendator_goto_recommend_enabled = false;
            //Ajax loader        
            $("#recommendator_goto_recommend").empty();
            $("#recommendator_goto_recommend").html("<img src='/templates/layout_images/recommendator/ajax-loader.gif' style='margin: 12px 0 0 0;' alt='' />");    
            $.get('/suosituskone/recommend/', function(data) {
                $('#recommendator').fadeOut(function() {
                    $('#recommendator').empty();
                    $('#recommendator').html(data);
                    $('#recommendator').fadeIn();
                    recommendator_goto_recommend_enabled = true;                                    
                });
            });
        }
    });       

    //Review: Seuraava resepti         
    var recommendator_next_enabled = true;
    $("#recommendator_review_next").live("click",function() {
        if (recommendator_next_enabled == true) {
            if (recommendator.current_recommendation != null) {
                //Save recommendation here with ajax post
                $.post("/suosituskone/", "add_grading=true&recipe_id=" + recommendator.current_recipe + "&grading=" + recommendator.current_recommendation);
            }        
            recommendator_next_enabled = false;
            $("#recommendator_review_next").empty();
            $("#recommendator_review_next").html("<img src='/templates/layout_images/recommendator/ajax-loader.gif' style='margin: 12px 0 0 0;' alt='' />");    
            $.get('/suosituskone/review/', function(data) {
                $('#recommendator').fadeOut(function() {
                    $('#recommendator').empty();
                    $('#recommendator').html(data);
                    $('#recommendator').fadeIn();                
                    recommendator_next_enabled = true;
                });
            });
        }
    });
    //Review: Quit    
    $("#recommendator_review_quit").live("click",function() {
            $("#recommendator_review_quit").empty();
            $("#recommendator_review_quit").html("<img src='/templates/layout_images/recommendator/ajax-loader-red.gif' style='margin: 12px 0 0 0;' alt='' />");    
            $.get('/suosituskone/finished/', function(data) {
                $('#recommendator').fadeOut(function() {
                    $('#recommendator').empty();
                    $('#recommendator').html(data);
                    $('#recommendator').fadeIn();                
                });
            });
    });      
    //Review: - 0 +
    $("a.recommendator_review_minus").live("click",function() {
        recommendator.setCurrentRecommendation(-1);
        $("a.recommendator_review_minus").addClass("recommendator_review_minus_active");
        $("a.recommendator_review_zero").removeClass("recommendator_review_zero_active");
        $("a.recommendator_review_plus").removeClass("recommendator_review_plus_active");    
    });
    $("a.recommendator_review_zero").live("click",function() {
        recommendator.setCurrentRecommendation(0);
        $("a.recommendator_review_minus").removeClass("recommendator_review_minus_active");
        $("a.recommendator_review_zero").addClass("recommendator_review_zero_active");
        $("a.recommendator_review_plus").removeClass("recommendator_review_plus_active");    
    });
    $("a.recommendator_review_plus").live("click",function() {
        recommendator.setCurrentRecommendation(1);
        $("a.recommendator_review_minus").removeClass("recommendator_review_minus_active");
        $("a.recommendator_review_zero").removeClass("recommendator_review_zero_active");
        $("a.recommendator_review_plus").addClass("recommendator_review_plus_active");    
    });
		      

    //Recommend: Fetch new recipes
    $("#recommendator_recommend_fetchnew").live("click",function() {
        //Ajax loader
        $("#recommendator_recommend_fetchnew").empty();
        $("#recommendator_recommend_fetchnew").html("<img src='/templates/layout_images/recommendator/ajax-loader.gif' style='margin: 12px 0 0 0;' alt='' />");    
        //Remove old recipes
        $("#recommendator_recommend div.recipes_container").hide();
        $("#recommendator_recommend div.recipes_container").empty();
        //Serialize form
        params = $("form#recommendator_recommend_params_form").serialize();
        //AJAX call        
        $.post("/suosituskone/recommendfetchnew/", params, function(data) {
            $('#recommendator_recommend div.recipes_container').html(data);            
            $('#recommendator_recommend div.recipes_container').slideDown();   
            $("#recommendator_recommend_fetchnew").empty();
            $("#recommendator_recommend_fetchnew").html("Hae uudet");                    
        });
    });   		     
		     
		        
});
//END DOCUMENT READY

var purchaselist_lists_visible = false;
function reposition_dock_purchaselist(toggle)
{
    num_items = recount_dock_purchaselist();
    if (purchaselist_lists_visible == false) {            
        $("#dock_purchaselist").css('bottom', 1);        
        if (toggle) {
            bottom_value = (num_items) * 24 + 1;
            $("#dock_purchaselist").css('bottom', bottom_value);        
            $("#dock_purchaselist_list").show();
            purchaselist_lists_visible = true;
        }
    }
    else {
        bottom_value = (num_items) * 24 + 1;
        $("#dock_purchaselist").css('bottom', bottom_value);        
        if (toggle) {
            $("#dock_purchaselist").css('bottom', 1);        
            $("#dock_purchaselist_list").hide();        
            purchaselist_lists_visible = false;
        }
    }  
}

function recount_dock_purchaselist() 
{
    num_items = $("#dock_purchaselist_list li").size();
    num_lists = num_items - 1;
    $("a#dock_purchaselist_toggle span").empty();    
    $("a#dock_purchaselist_toggle span").append(""+num_lists);
    return num_items;
}



function merkitseKommentti(id)
{
    pars = 'denunciation=true&kohde=kommentti&kommentti_id='+id;
    if(confirm('Oletko varma?')){
        $.post('/ajaxHandler.php', pars, function(data, status){
            kiitos();
        });
    }
}
function merkitseReseptienergia(id)
{
    if(confirm('Oletko varma?'))
    {
        var ajax = new Ajax.Request('/ajaxHandler.php', {parameters:'toiminto=denunciation&kohde=resepti&resepti_id='+id,method:'get', onComplete: kiitos});
    }
}
function kiitos(){
    alert('Kiitos ilmoituksesta!');
}

function recommendRecipe(){
    $('#jquery_helper_progress').html('<img src="http://static.kotikokki.net/templates/layout_images/ajax-loader-small-2F2820-on-white.gif" />');
    cur_page = $(location).attr('href');
    pars = $('#recipe_recommendation_form').serialize();
    $.post(cur_page, pars, function(data, status){
        $('#recipes_view_thumbs').html(data);
    });
}
function recommendObject(){
    cur_page = $(location).attr('href');
    pars = $('#object_recommendation_form').serialize();
    $.post(cur_page, pars, function(data, status){
        $('#jquery_helper_thumber').html(data);
    });
}
function vote_object()
{
    // $('#jquery_helper_progress').html('<img src="http://static.kotikokki.net/templates/ajax-loader.gif" />');
    cur_page = $(location).attr('href');
    pars = $('#recipe_vote_form').serialize();
    $.post(cur_page, pars, function(data, status){
        $('#recipes_view_vote').replaceWith(data);
    });
}

function showWiki(e, article, element){
    param = 'wikipopup=true&article='+article;
    $.ajax({
        data: param,
        url: '/ajaxHandler.php',
        type: 'POST',
        success: function(html){
            $('#windowContent').html(html);
        }
    });

    if($('#window').css('display') == 'none') {
        $('#window').show();
    }
    return false;
}
function saveIngredientSynonym(){
    var ajax = new Ajax.Request('/ajaxHandler.php', {onLoading:function(request){effekti()},parameters:Form.serialize(document.forms['synonym'])+'',method:'post'});
}
function recipe_images_buttonPrevCallback(carousel, button, enabled){
  if(enabled){
    $(button).attr("disabled", "");
    jQuery('#prev_image').removeClass("recipes_view_image_scrollButtonLeft_disabled");
    jQuery('#prev_image').addClass("recipes_view_image_scrollButtonLeft");
  }
  else{
    $(button).attr("disabled", "disabled");
    jQuery('#prev_image').removeClass("recipes_view_image_scrollButtonLeft");
    jQuery('#prev_image').addClass("recipes_view_image_scrollButtonLeft_disabled");
  }
}
function recipe_images_buttonNextCallback(carousel, button, enabled){
  //  jQuery('#prev_image').removeClass("recipes_view_image_scrollButtonLeft_disabled");
  //  jQuery('#prev_image').addClass("recipes_view_image_scrollButtonLeft");
  if(enabled){
    $(button).attr("disabled", "");
    jQuery('#next_image').removeClass("recipes_view_image_scrollButtonRight_disabled");
    jQuery('#next_image').addClass("recipes_view_image_scrollButtonRight");
  }
  else{
    $(button).attr("disabled", "disabled");
    jQuery('#next_image').removeClass("recipes_view_image_scrollButtonRight");
    jQuery('#next_image').addClass("recipes_view_image_scrollButtonRight_disabled");
  }
}
function recipe_images_initCallBack(carousel){
  jQuery('#recipe_images').removeClass('piilota');
  jQuery('#next_image').bind('click', function() {
    carousel.next();
    return false;
  });

  jQuery('#prev_image').bind('click', function() {
    carousel.prev();
    return false;
  });
}

function recipes_newest_changePage(muutos,linkki) {
    if(running)
    {
        return false;
    }
    running = true;
    recipe_newest_page = recipe_newest_page+muutos;
    images = '';
    if(imagesOnly)
    {
        images = 'imagesonly=true';
    }
    if(recipe_newest_page<0)
    recipe_newest_page = 0;
    var pars = "ajax=true&recipes_newest_page="+recipe_newest_page+"&"+images;
    $.ajax({
        data: pars,
        url: '/reseptit/',
        type: 'POST',
        success: function(html){
            $('#recipes_newest_content').html(html);
            $('#imagetoggler').attr('disabled', false);
            running = false;
        }
    });
}
function recipe_newest_toggleImages(){
    $('#imagetoggler').attr('disabled', true);
    if(imagesOnly)
    {
        imagesOnly = false;
    }
    else
    {
        imagesOnly = true;
    }
    recipes_newest_changePage(0);
    return false;
}
function recipeCollections_getCollectionsAlphabetically(kirjain) {
    var pars = "ajax=true&recipeCollectionsAlphabetically=true&alphabet="+kirjain;
    $.ajax({
        data: pars,
        url: '/ajaxHandler.php',
        type: 'POST',
        success: function(html){
            $('#recipeCollectionsAlphabetically').html(html);
        }
    });
    return false;
}
jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});


// Suosituskone
function Recommendator()
{
    this.current_recipe = false;
    this.setCurrentRecipe = function(id)
    {
        this.current_recipe = id;
    }
    this.current_recommendation = null;
    this.setCurrentRecommendation = function(id)
    {
        this.current_recommendation = id;
    }

}
function recommendator_removehate(name, id)
{
    $.post("/suosituskone/", 'remove_inhokki='+name);
    $('#recommendator_hate_inhokki_remove_li_' + id).remove();
    $("#recommendator_hate_inhokki span.list_full").hide();        
    return false;
}
function recommendator_add_hate()
{
    num_items = $("ul#jquery_helper_inhokkilist li").size();
    if (num_items < 5) {
        $.post("/suosituskone/", $('#recommendator_hate_inhokki_form').serialize(),
        function(data)
        {
            data = $.parseJSON(data);
            $('#jquery_helper_inhokkilist').empty();
            for (var i in data)
            {
                html = ("<li class='jquery_helper_inhokit' id='recommendator_hate_inhokki_remove_li_" + i + "'><a id='recommendator_hate_inhokki_remove_" + i + "' class='remove' href='#' onclick='recommendator_removehate(\"" + data[i]['id'] + "\", " + i +");return false;'>&nbsp;</a><span class='name'>" + data[i]['name'] + "</span></li>");
                $('#jquery_helper_inhokkilist').append(html);
                
                $("#recommendator_hate_inhokki_form input.text").val('');
            }
            if ((num_items+1) == 5) {
                $("#recommendator_hate_inhokki span.list_full").show();        
            }
                    
        }); 
    }
    return false;
}