/**
* Ajax fix voor page reload
*/
if (document.location.href.search(/#/) != -1) {
var url = document.location.href.split("#");
document.location.href = url[1];
}

$(document).ready( function() {
    initHistory();
    setBehaviour();
});

includeScript("/scripts/messages.js");

function setBehaviour() {

    $('a.closeDialog').unbind('click');
    $('a.lightbox').unbind('click');
    $('a').unbind('click');
    $('a.ajax').unbind('click');
    $('tr').unbind('click');
    $('form').unbind('submit');

    $('a.lightbox').click( function(event) {
    	event.preventDefault();
        var redirecturl = $(this).attr('redirecturl');
        if(redirecturl) {
            $.get($(this).attr('href'));
            lightbox(redirecturl);
        } else {
            lightbox($(this).attr('href'));
        }
        //return false;
    });

    $('a.ajax').click( function() {
    	var confirmText = $(this).attr('confirm');
        var redirecturl = $(this).attr('redirecturl');
        var noshistory = $(this).attr('nohistory');

        if (confirmText) {
            if (confirm(confirmText)) {
                ajax_load(this.href, redirecturl, noshistory);
            } else {
                notify("Action cancelled.");
            }
        } else {
            ajax_load(this.href, redirecturl, noshistory);
        }
        
        if($(this).attr('close')) {
            $.modal.close();
        }
        
        return false;
    });

    $('a.closeDialog').click( function() {
        $.modal.close();
        return false;
    });
    
    $('.disabled').attr("title","Je kunt hiervan gebruik maken als je bent ingelogd.");
    $('.disabled').click( function() {
        notify('Je kunt hiervan gebruik maken als je bent ingelogd.');
        return false;
    });
    
    $('form.ajax').submit( function() {
        
        var errorFeedbackArray = new Array();
        
        var formError = false;
        var redirecturl = $(this).attr('redirecturl');
        var stopredirect = 0;

        $(this).find(":input").each(
        function(i, input) {
            if ($(input).attr('required'))
            if (!$(input).val() && !$(input).attr('checked') ) {
            	var title = $(input).attr('title');
            	if ($(input).attr('required') != 'true') {
            		title = $(input).attr('title');
            	}
            	if (!title) {
            		title = $(input).attr('name');
            	}
                errorFeedbackArray.push("Veld verplicht '" + title + "'");
                formError = true;
            } else if(!$(input).val() == '-kies-'){
                errorFeedbackArray.push("Veld verplicht '" + title + "'");
                formError = true;

            }

        });
       
        // controlleert of required selects als selected value "-kies-" hebben // nog niet getest in IE
        $(this).find("select").each( function(i, input) {
            if ($(input).attr('required')){
                $(input).find('option').each(
                function(id,option){
                    if($(option).attr('selected')){
                        if($(option).val() == "-kies-"){
                            errorFeedbackArray.push("Veld verplicht '" + $(input).attr('title')+ "'");
                            formError = true;
                        }
                    }
                });
            }
        });

        $(this).find(":checkbox").each( function() {      
            if ($(this).attr('required')) {                            
                if (!$(this).is(":checked")) {                   
                    formError = true;
                    errorFeedbackArray.push("Veld verplicht '" + $(this).attr('title')+ "'");  
                }
            }
        });
        
        if (formError) {
            // indien errors, geef ze weer en submit niet 
            
             notify(errorFeedbackArray.join('<br><br>'),'notify');
            
            return false;
        }        
        $('body').append('<div id="loading">Pagina wordt geladen</div>');

        var hasFile = 0;
        $(this).find('input:file').each( function(i, input) {
            if ($(input).val())
            hasFile++;
        });
        if ($(this).hasClass('lightbox')) {
            
            var lightbox = 1;
            createlightbox();

        } else {
            var lightbox = 0;
        }
        if ($(this).hasClass('closeDialog')) {
            $.modal.close();
        } 

        if (hasFile > 0) {
            // $(this).append("<input type='hidden'
            // name='fileform' value='1' />");
            $(this).ajaxSubmit( {
                data : {
                    fileform :true,
                    lightbox :lightbox
                },
                success : function(data) {
                    // stukje code om de response te kunnen
                    // parsen
                	
                	
                    data = data.replace('<textarea>', '');
                    data = data.replace('</textarea>', '');
                    data = data.replace('<TEXTAREA>', '');
                    data = data.replace('</TEXTAREA>', '');
                    data = data.replace(/&lt;/g, '<');
                    data = data.replace(/&gt;/g, '>');

                    data = eval('(' + data + ')');
                    $.each(data, function(i, div) {
                        if (div.id == 'notify') notify(div.message, div.type);
                        else if (div.id == 'stopredirect') stopredirect = 1;
                        else $("#" + div.id).html(div.html);
                    });
                    if (!lightbox)
                    $.modal.close();
                    if (!stopredirect && redirecturl) {
                        ajax_load(redirecturl);
                    } else {
                        setBehaviour();
                    }
                    $('#loading').remove();
                }
            });
        } else {
            $(this).ajaxSubmit( {
                data : {
                    lightbox :lightbox
                },
                success : function(data) {
                   data = eval('(' + data + ')');
                    $.each(data, function(i, div) {
                        if (div.id == 'notify')
                        notify(div.message, div.type);
                        else if (div.id == 'stopredirect')
                        stopredirect = 1;
                        else
                        $("#" + div.id).html(div.html);
                    });
                    if (!lightbox) $.modal.close();
                    if (!stopredirect && redirecturl) {
                        ajax_load(redirecturl);
                    } else {
                        setBehaviour();
                    }
                    $('#loading').remove();
                }
            });
        }
        return false;
    });

    $('.datepicker').datepicker({
        dateFormat :'dd-mm-yy'
    });

    // Initieer draggable objecten
    $(".tabs").tabs();

    $('tr.cookstep').click( function() {
        $('tr.cookstep').removeClass('step_on');
        $(this).addClass('step_on');
    });

    $('input.numeric').each( function() {
        $(this).numeric();
    });

    $('input.ingredient_tags').click( function() {
        if ($(this).attr('checked'))
        $('input.ingredient_tag').attr('checked', 'checked');
        else
        $('input.ingredient_tag').removeAttr('checked');
    });

    var datePointerWidth = $('.date_pointer_middle').width()*-1;
    $('div#plan_agenda div.plateday div.date_pointer').css('left', (datePointerWidth+42)/2);
    $('div#plan_agenda div.plateday div.date_pointer').width($('.date_pointer_middle').width()+40);
            
    $('div#offerbox_content').width($('#offerbox_content').children().size()*98);
    
    $("input[type=file]").each( function() {
        var intendedWidth = 195;
        if ($(this).hasClass('noFancy')) {
			return;
		}
        if($(this).hasClass('file_knop_roze')){
        
            if ($(this).width() != intendedWidth) {
                $(this).filestyle( {
                    image :"/images/knoppen/bladeren_roze.png",
                    imageheight :19,
                    imagewidth :82,
                    width :intendedWidth
                });
            }
        } else {
            if ($(this).width() != intendedWidth) {
                $(this).filestyle( {
                    image :"/images/knoppen/bladeren_groen.png",
                    imageheight :19,
                    imagewidth :82,
                    width :intendedWidth
                });
            }  
            
        }
    
    });

    $(".contact").hover( function() {
        $(this).addClass("message_on");
    }, function() {
        $(this).removeClass("message_on");
    });

    $(".message").hover( function() {
        $(this).addClass("message_on");
    }, function() {
        $(this).removeClass("message_on");
    });

    $(".message").click( function() {
        var id = $(this).attr("itemid");
        lightbox("/messages/read?id=" + id);
    });
    
    var maxHeight = 0;
    $('.same_height').each(
        function(i, eenElement) {         
           if ($(eenElement).height() > maxHeight) {
               maxHeight = $(eenElement).height();
           }
           
    });
    $('.same_height').height(maxHeight);
    
    var maxHeightModal = 0;
    
    $('.same_height_modal').each( 
        function(i, eenElement) { 
            if ($(eenElement).height() > maxHeightModal) { 
                maxHeightModal = $(eenElement).height(); 
            } 
        
    }); 
    $('.same_height_modal').height(maxHeightModal); 
 	     
    initAutocomplete();

    // Voeg inline menu's toe aan div elementen
    window.setTimeout("initContextMenus()", 500);

    $('input').mouseup(function(){
    	$(this).focus();
    	//window.setTimeout("$(this).focus()", 100);
    });
}


function initPlanner() {
    $("div.slidebox").each(function(){
    	$(this).find('ul').css({width: '10000px'});
     	var left  = $(this).find('.left');
    	var right = $(this).find('.right');
    	var mid   = $(this).find('.mid');
    	
    	mid.serialScroll({
            items: 'li',
            prev: left,
            next: right,
            step: 4,
            axis: 'x',
            start: 0, 
            duration:600,
            force:true,
            stop:true,
            lock: true,
            cycle: false, 
            easing:'easeOutQuart',
            jump: false 
        });
        
    });
    
    $('.profile').click(function(){
    	var profile_id = $(this).attr("itemid");
    	if ($(this).hasClass('selected')) {
        	$('input[name=profile_id]').val('');
        	$('.profile').removeClass('selected');
    	} else {
        	$('input[name=profile_id]').val(profile_id);
        	$('.profile').removeClass('selected');
        	$(this).addClass('selected');
    	}
    	$('form#plan.ajax').submit();
    });

    $('.platetype').click(function(){
    	var platetype_id = $(this).attr("itemid");
    	if ($(this).hasClass('selected')) {
        	$('input[name=platetype_id]').val('');
        	$('.platetype').removeClass('selected');
    	} else {
        	$('input[name=platetype_id]').val(platetype_id);
        	$('.platetype').removeClass('selected');
        	$(this).addClass('selected');
    	}	
    	$('form#plan.ajax').submit();
    });
    
}


function initContextMenus() {
	$("div[menu]").each( function() {

		var inform = $("a.inform", this);
        $(this).bind('click', function() {
			inform.each(function() {
				$.post(this.href);
			});	
		});


		$(this).contextMenu( {
	        menu :$(this).attr("menu")
	    },
	    function(menuElement, sourceElement) {
	        
	        
	    	// Breid de url uit met de id van het bron element
	        var url = menuElement.attr('href');
	        var nohistory = menuElement.attr('nohistory');
	        var id = sourceElement.attr('itemid');
	        var redirecturl = menuElement.attr('redirecturl');
	        var target = menuElement.attr('target');
	        if (target){
	        	open.window(url);
	        	return false;
	        }	
	        if (url.search(/\?/) > -1)
	        url = url + '&id=' + id;
	        else
	        url = url + '?id=' + id;
	
	        // Kijk nu wat we met de link gaan doen
	        if (menuElement.hasClass('lightbox')) {
	            lightbox(url, true);
	        } else if (menuElement.hasClass('ajax')) {
	            ajax_load(url, redirecturl, nohistory);
	        } else if (menuElement.hasClass('script')) {
	            var callback = menuElement.attr('href');
	            callback = callback.replace("javascript:", "");
	            callback = callback.replace(")", "");
	            callback = callback.replace("(", "");
	            window[callback](id);
	        } else {
	            document.location.href = url;
	        }
	        
	    });
	    $(this).css("cursor", "pointer");
	});

	function initMenu(menuElement, sourceElement) {

	}
}



function initAutocomplete() {
    $('input').each( function() {
        if ($.isFunction($(this).autocomplete()) == false) {
            var url = $(this).attr('autocompleteurl');

            // if (url) $(this).autocomplete(url);
            if (url) {
                $(this).unbind();
                if ($(this).attr('autocompletematch')) {
                    $(this).autocomplete(url, {
                        mustMatch :false
                    });
                } else {
                    $(this).autocomplete(url);
                }
                $(this).result(
                	function(event, data, formatted) {
                		$(this).parents('form').append('<input type=hidden value=1 name="autocompleted_' + $(this).attr('name') + ' />');
                		$(this).parents('form').append('<input type=hidden value=1 name="autocompleted" />');
                });
            }
        }
    });
}

// Laad een javascript
function includeScript(uri, callback) {
    var script = document.createElement("script");
    script.src = uri;
    script.type = "text/javascript";
    script.language = "javascript";
    if (callback != null) {
        script.onreadystatechange = function() {
            if (script.readyState == "complete")
            callback();
        };
        script.onload = callback;
    }
    document.getElementsByTagName("head")[0].appendChild(script);
    return false;
}

// Laad een stylesheet
function includeStyle(uri) {
    $("head").append(
    "<link rel='stylesheet' type='text/css' href='" + uri + "' />");
}

// History - AJAX calls
function initHistory() {
    // Start ajax history
	if (window.dhtmlHistory.isSafari) {
		/*
	    $.history.addListener(function(newLocation, historyData) {
	    	if (newLocation == null) {
	        	newLocation = document.location.href;
	        }
	        else if (oldLocation != newLocation) {
	    		//ajax_load(newLocation);
	        	document.location.href = newLocation;
	        }
	    	if (newLocation == '/' && historyData == null && oldLocation != ""){
	        	document.location.href = document.location.href;
	        }	
	    	//notify(newLocation +" | "+ oldLocation);
	        oldLocation = newLocation;
	        
		});
		*/
		return false;
	} else  {
	    $.history.addListener(function(newLocation, historyData) {
	    	if (newLocation == "") {
	        	newLocation = "/";
	        }
	        else if (oldLocation != newLocation) {
	    		ajax_load(newLocation);
	        }
	    	if (newLocation == '/' && historyData == null && oldLocation != ""){
	        	document.location.href = document.location.href;
	        }	
	        oldLocation = newLocation;
		});
	}
	
}

var oldLocation;

/**
* Laadt een url via ajax
*/
function ajax_load(alink, redirectUrl, noHistory) {
	// Voor back/forward knoppen
    var stopredirect = 0;
    if (!noHistory){
    	$.history.add(alink, alink);
    	//$.history.load(alink);
    }
    $('body').append('<div id="loading">Pagina wordt geladen</div>');

    $.get(alink, function(data) {       
    	if (data.substr(0,1) == '<') {
    		document.location = "/";
    	}
        else {
            data = eval('(' + data + ')');
            $.each(data, function(i, div) {
                if (div.id == 'notify') {
                    notify(div.message, div.type);
                } else if (div.id == 'stopredirect') {
                    stopredirect = 1;
                } else if (div.id == 'debug') {
                    Debug.write(div.message, div.name);
                } else
                $("#" + div.id).html(div.html);
            });
        }
        $('#loading').remove();
        // Zet behaviour opnieuw
        if (!stopredirect && redirectUrl) {
            ajax_load(redirectUrl);
        } else {
           setBehaviour();
        }
    });
}

function lightbox(url) {
    
    createlightbox();

    if (url.search(/\?/) > -1) url = url + '&lightbox=true';
    else url = url + '?lightbox=true';
    ajax_load(url, null, true);
}

function createlightbox(){
   var padding = 20;
   
   var lightboxHeight = $(window).height()-(parseInt(padding)+parseInt(padding));

   lightboxHeight = Math.round(lightboxHeight*0.8);
   
   var containerHeight = lightboxHeight;
  

    $.modal('<div id="lightbox" style="width:663px; overflow-x:none;"><center><h3 style="color:#bbb">-pagina wordt geladen-</h3></center></div>',
    {
        containerCss : {
            height: containerHeight+'px',
            width :'680px',
            padding :'10px'
            //overflow:'hidden'
        },
        onShow : function() {
            
            // alert(lightboxHeight);
            // ajax_load($(this).attr('href'));
            $('.simplemodal-data').css('height',containerHeight+'px');
            
            $('.simplemodal-data').css('overflow-y','auto');
            
        },
        onClose : function() {
            $.modal.close(); // must call this!
        }

    });
    
}

function initBeautyModal(){
    $('#modal_table').css('width','608px');
   
    $('#simplemodal-container').css('background-color','transparent');    
    $('#simplemodal-container').css('border','none');
  
    $('#simplemodal-container').css('top','100px');
    $('.simplemodal-close').css('top','0px');
    
    $('.simplemodal-data').find('div.innermodal').find('div#content_modal').css('height',$('.simplemodal-data').height()-40+'px');
   
    $('.modalCloseImg').css('margin-right','64px');
    $('.modalCloseImg').css('margin-top','13px');
   
   
    
}

function progressbar(url, barid) {
    var timestamp = new Date().getTime();
    $.get(url, {
        barid :barid,
        stamp :timestamp
    }, function(data) {
        if (!data)
        return;
        var response;
        eval("response = " + data);
        if (!response)
        return;
        var percentage = Math.floor(100 * parseInt(response['bytes_uploaded'])
        / parseInt(response['bytes_total']));
        $("#progressbar").progressBar(percentage);
    });
    // setTimeout("progressbar('"+url+"', '"+barid+"')", 3000);

}

var notifier = 0;
function notify(message, type) {
    notifier++;
    if (!$('#notifier').attr('id')) {
        $('#content').append("<div id='notifier'></div>");
    }
    $('#notifier').append(
    "<div id='not" + notifier + "' class='notification'>" + message
    + "</div>");
    $('#notifier').css('top', 100 + $(window).scrollTop());
    window.setTimeout("$('#not" + notifier + "').fadeOut()", 2000);
}

/* Debug functies */

// We gaan een debug object beginnen
window.Debug = {
    output :null, // Het debug vensters
    div :null,
    windiv :null,
    winoutput :null,

    popup : function() {
        debugWindow = window.open('/index/debug', 'debugWindow',
        'width=550px, height=450px, menubar=false');
        window.setTimeout( function() {
            Debug.windiv = debugWindow.$('#debug');
            Debug.winoutput = debugWindow.$('#debugscreen');
            Debug.winoutput.html(Debug.output.html());
            Debug.hide();
        }, 1000);

    },

    initialize : function() {
        if (!this.output) {
            $('body').append("<div id='debug'>Debug scherm <a onclick='Debug.popup()'>(window)</a><div id='debugscreen'></div></div>");
            this.div = $('#debug');
            this.output = $('#debugscreen');
        }
    },

    write : function(message, label) {
        if (!this.output) this.initialize();
        var dat = new Date;
        dat = dat.toLocaleTimeString();
        this.output.prepend("<fieldset><legend>" + dat + " - " + label
        + "</legend><pre>" + message + "</pre></fieldset>");
        // if (this.windiv) this.windiv.html(this.div.html());
        if (this.winoutput) this.winoutput.html(this.output.html());
    },

    hide : function() {
        this.div.fadeOut();
    },

    close : function() {
        $('#debug').remove();
        this.output = null;
    }
}

// Ingredientregel toevoegen aan recept
function addIngredient() {
    var html = '<tr class="ingredient">';
    html += '<td><input type="text" name="amount[]" onkeypress="return isNumeric(this, event);" class="input_small"  /></td>';
    html += '<td><input type="text" name="unit[]" class="input_small" /></td>';
    html += '<td><input type="text" name="ingredient[]" class="input_medium" /></td>';
    html += '<td><img onclick="$(this).parents(\'tr.ingredient\').remove()" src="/images/icons/delete.gif" title="Verwijderen" /></td></tr>';
    $('#ingredients').append(html);
}

function userAddIngredient() {

    var currentIngredients = $('#ingredients').find('tr.ingredient');

    var newNr = currentIngredients.length + 1;

    var html = '<tr class="ingredient">';
    html += '<td class="td_label_ingredient">Ingredient '+newNr+'</td>';
    html += '<td><input type="text" name="amount[]" onkeypress="return isNumeric(this, event);" class="width_92"  /></td>';
    html += '<td><input autocompleteurl="/thesaurus/completewithpref?toplevelid=7" type="text" name="unit[]" class="width_92" /></td>';
    html += '<td><input autocompleteurl="/thesaurus/completewithpref?toplevelid=1" type="text" name="ingredient[]" class="width_289" /></td>';
    html += '<td><img onclick="$(this).parents(\'tr.ingredient\').remove()" src="/images/iconen/kruis_wit_roze.png" title="Verwijderen" /></td></tr>';
    $('#ingredients').append(html);

    initAutocomplete();
}

// Bereidinsstap toevoegen aan recept
function addStep() {
    var html = '<tr class="step">';
    html += '<td><textarea class="step" name="steps[]"></textarea></td>';
    html += '<td>';
    html += '<a onclick="userPrepstepup($(this).parents(\'tr.step\'))" class="pointer">';
    html += '<img src="/images/icons/up.gif" title="Omhoog" />';
    html += '</a>';
    html += '<a onclick="userPrepstedown($(this).parents(\'tr.step\'))" class="pointer">';
    html += '<img src="/images/icons/down.gif" title="Omlaag" />';
    html += '</a>';
    html += '<a onclick="$(this).parents(\'tr.step\').remove()" class="pointer">';
    html += '<img src="/images/icons/delete.gif" title="Verwijderen" />';
    html += '</a>';
    html += '</td>';
    html += '</tr>';
    $('#preparation').append(html);
}

// Bereidinsstap toevoegen aan recept
function userAddStep() {

    // hoeveel stappen hebben we reeds ?
    // wat is het nieuwe volg nummer ? (sequence)

    var new_sequence_nr =  parseInt($('#preparation').find('tr.step:last').attr('sequence')) + 1;

    if(!new_sequence_nr){
        new_sequence_nr = 1;
    }

    var html = '<tr class="step" sequence="'+new_sequence_nr+'">';

    html += '<td class="preperation_step_sequence td_label">Regel '+new_sequence_nr+'</td>';
    html += '<td><textarea class="" name="steps[]" style="width:534px;"></textarea></td>';
    html += '<td>';
    html += '<a onclick="$(this).parents(\'tr.step\').remove()" class="pointer">';
    html += '<img style="margin-left:3px;" src="/images/iconen/kruis_wit_roze.png" title="Verwijderen" />';
    html += '</a>';
    html += '<br>';
    html += '<a onclick="userPrepstepup($(this).parents(\'tr.step\'))" class="pointer">';
    html += '<img src="/images/knoppen/pijl_boven_roze.png" title="Omhoog" />';
    html += '</a>';
    html += '<br><br>';
    html += '<a onclick="userPrepstepdown($(this).parents(\'tr.step\'))" class="pointer">';
    html += '<img src="/images/knoppen/pijl_onder_roze.png" title="Omlaag" />';
    html += '</a>';

    html += '</td>';
    html += '</tr>';
    $('#preparation').append(html);
}

function userPrepstepup(tr) {
    var newtr = tr.clone();
    if (!$(newtr).find('textarea').val()) {
    	$(newtr).find('textarea').val($(tr).find('textarea').val());
    }	

    var prev = tr.prev();
    if (prev.hasClass('step')) {
        prev.before(newtr);
        $(newtr).attr('sequence',$(prev).attr('sequence'));
        $(newtr).find('td.preperation_step_sequence').text('Regel '+ $(newtr).attr('sequence'));
        $(prev).attr('sequence',$(tr).attr('sequence'));
        $(prev).find('td.preperation_step_sequence').text('Regel '+ $(tr).attr('sequence'))

        tr.remove();

    }
}

function userPrepstepdown(tr) {
    var newtr = tr.clone();
    if (!$(newtr).find('textarea').val()) {
    	$(newtr).find('textarea').val($(tr).find('textarea').val());
    }	
        
    var next = tr.next();
    if (next.hasClass('step')) {
        next.after(newtr);
        $(newtr).attr('sequence',$(next).attr('sequence'));
        $(newtr).find('td.preperation_step_sequence').text('Regel '+ $(newtr).attr('sequence'));
        $(next).attr('sequence',$(tr).attr('sequence'));
        $(next).find('td.preperation_step_sequence').text('Regel '+ $(tr).attr('sequence'))
        tr.remove();
    }
}

// Tag toevoegen
function addTag() {
    var aspect = $('#newaspect :selected').text();
    var aspect_id = $('#newaspect').val();
    var tag = $('#newtag').val();

    var html = '<tr class="tag">';
    html += '<td>' + aspect
    html += '<input type="hidden" name="aspects[]" value="' + aspect_id + '">';
    html += '</td>';
    html += '<td>' + tag;
    html += '<input type="hidden" name="tags[]" value="' + tag + '">';
    html += '</td>';
    html += '<td><a href="#" onclick="$(this).parents(\'tr.tag\').remove();  return false;">[X]</a></td>';
    html += '</tr>';
    $('#tags').append(html);
    $('#newtag').val('');
}

// Regel toevoegen aan profiel
function addRule() {
    var aspect = $('#newaspect :selected').text();
    var aspect_id = $('#newaspect').val();
    var tag = $('#newtag').val();
    var group = $('#newgroup').val();
    var condition = $('#newcondition').val();

    var html = '<tr class="rule">';
    html += '<td><input name="groupnames[]" value="' + group + '" /></td>';
    html += '<td>' + aspect
    html += '<input type="hidden" name="aspects[]" value="' + aspect_id + '">';
    html += '</td>';
    html += '<td>' + tag;
    html += '<input type="hidden" name="tags[]" value="' + tag + '">';
    html += '</td>';
    html += '<td>';
    html += '<select name="conditions[]">';
    if (condition == 1) {
        html += '<option value="1" selected>wel</option>';
        html += '<option value="0">niet</option>';
    } else {
        html += '<option value="1">wel</option>';
        html += '<option value="0" selected>niet</option>';

    }
    html += '</select>';
    html += '</td>';
    html += '<td><a href="#" onclick="$(this).parents(\'tr.rule\').remove()">[X]</a></td>';
    html += '</tr>';

    $('#newtag').val('');
    $('#rules').append(html);
    initAutocomplete();
}

// Regel toevoegen aan profiel
function addPreference(like) {
	if(like) {
		var el = $('#newlike');
	}
	else {
		var el = $('#newdislike');
	}

	var url = el.attr('autocompleteurl') + '&q=' + el.val() + '&limit=10&timestamp=';
	
	$.getJSON(url, function(json) {
		if(json.length == 0) {
			notify('Culios kent geen ' + el.val());
		}
		else {
			 if (like) {
        		var tag = $('#newlike').val();
        		var html = '<div class="rule">';
        		html += tag;
        		html += ' <a href="#" onclick="$(this).parents(\'div.rule\').remove(); return false;"><img title="Verwijder dit ingredient" alt="X" src="/images/iconen/kruis_grijs.png" class="icoon_right" /></a>';
        		html += '<input type="hidden" name="tagslike[]" value="' + tag + '" />';
        		$('#newlike').val('');
        		if (tag) $('#like').append(html);
        		else notify("Vul eerst een ingredient in.");
    		} else {
        		var tag = $('#newdislike').val();
        		var html = '<div class="rule">';
        		html += tag;
        		html += '<a href="#" onclick="$(this).parents(\'div.rule\').remove(); return false;"><img title="Verwijder dit ingredient" alt="X" src="/images/iconen/kruis_grijs.png" class="icoon_right" /></a> ';
        		html += '<input type="hidden" name="tagsdislike[]" value="' + tag + '" />';
        		$('#newdislike').val('');
        		if (tag) $('#dislike').append(html);
        		else notify("Vul eerst een ingredient in.");
    		}
			
			initAutocomplete();
		}
	});
/*
    if (like) {
        var tag = $('#newlike').val();
        var html = '<div class="rule">';
        html += tag;
        html += ' <a href="#" onclick="$(this).parents(\'div.rule\').remove(); return false;"><img title="Verwijder dit ingredient" alt="X" src="/images/iconen/kruis_grijs.png" class="icoon_right" /></a>';
        html += '<input type="hidden" name="tagslike[]" value="' + tag + '" />';
        $('#newlike').val('');
        if (tag) $('#like').append(html);
        else notify("Vul eerst een ingredient in.");
    } else {
        var tag = $('#newdislike').val();
        var html = '<div class="rule">';
        html += tag;
        html += '<a href="#" onclick="$(this).parents(\'div.rule\').remove(); return false;"><img title="Verwijder dit ingredient" alt="X" src="/images/iconen/kruis_grijs.png" class="icoon_right" /></a> ';
        html += '<input type="hidden" name="tagsdislike[]" value="' + tag + '" />';
        $('#newdislike').val('');
        if (tag) $('#dislike').append(html);
        else notify("Vul eerst een ingredient in.");
    }
    initAutocomplete();
	*/
}

function showlog() {
    ajax_load("/demo_debug/showlog");
}

function showStores(id) {
    $('#amount' + id).slideUp('slow');
    $('#stores' + id).slideDown('slow');
}
function showAmountOfStores(id) {
    $('#stores' + id).slideUp('slow');
    $('#amount' + id).slideDown('slow');
}

function prepstepup(tr) {
    var newtr = tr.clone();
    var prev = tr.prev();
    if (prev.hasClass('step')) {
        prev.before(newtr);
        tr.remove();
    }
}

function prepstepdown(tr) {
    var newtr = tr.clone();
    var next = tr.next();
    if (next.hasClass('step')) {
        next.after(newtr);
        tr.remove();
    }
}

// Selecteer een keuken (/plan/planner)
function selectKitchen(id) {
    var profile = $(".profile[itemid=" + id + "]");
    if (profile.hasClass('selected')) {
        $(".profile").removeClass('selected');
        $("input[name=profile_id]").val('');
    } else {
        $(".profile").removeClass('selected');
        profile.addClass('selected');
        $("input[name=profile_id]").val(id);
    }

}



//Selecteer een altplate (/plan/planner)
function selectAlt(id) {
    var profile = $(".altplate[itemid=" + id + "]");
    if (profile.hasClass('selected')) {
        $(".altplate").removeClass('selected');
        $("input[name=altplate]").val('');
    } else {
        $(".altplate").removeClass('selected');
        profile.addClass('selected');
        $("input[name=altplate]").val(id);
    }

}


/**
 * Init voor functionaliteit in avatar selectie
 */

function initAvatarSelect(){
    $('.avatar_to_select').click(
        function(){
            $('.avatar_to_select').removeClass("active_img");
            $(this).addClass("active_img");    
            $('#selected_avatar').val($(this).attr('id'));
            $('#selected_avatar_image').attr('src',$(this).find('img').attr('src'));
            $('#selected_avatar_image').attr('src',$(this).find('img').attr('src'));
     
        });
        $('#save_avatar').click(
        function(){
            //$('#active_avatar_image').attr('src',$('#selected_avatar_image').attr('src'));
            
            setTimeout('$.modal.close()',1000);
            $('#active_avatar_image').attr('src',$('#selected_avatar_image').attr('src'));
            
            //console.log($('#selected_avatar_image').attr('src'));
            //alert('change');
            //setTimeout('$.modal.close()',5000);
            //return false;
            
            
        });
        
        
}

function agendaControl(el,direction,url){
    
    // create an javascript date opbject of the current selected date
    
    
    var splittedDate = $(el).attr('date').split('-');    
    var lastDate = new Date();        
    lastDate.setFullYear(splittedDate[0]);
    
    if(splittedDate[2].charAt(0) == 0){

        lastDate.setDate(splittedDate[2].charAt(1));
    }else{
        lastDate.setDate(splittedDate[2]);
    }     
    
    if(splittedDate[1].charAt(0) == 0){
        lastDate.setMonth(parseInt(splittedDate[1].charAt(1))-1);
    }else{
        lastDate.setMonth(parseInt(splittedDate[1])-1);
    }

    var aWeekInSeconds = 1*60*60*24*7*1000;

    var newDate = new Date();
      
    if(direction == 'backward'){
            
         var lastWeek = parseInt(lastDate.getTime()) - parseInt(aWeekInSeconds); 
        newDate.setTime(lastWeek);
    }
    
    if(direction == 'forward'){
        
        var nextWeek = parseInt(lastDate.getTime()) + parseInt(aWeekInSeconds); 
        newDate.setTime(nextWeek);
  
    }
   
    var month = parseInt(newDate.getMonth())+1;
    
    if(month < 10){
        month = '0'+month;
    }
    
    var day = newDate.getDate();
    
    if(day < 10){
        day = '0'+day;
    }    
    
    ajax_load(url+"?date="+newDate.getFullYear()+'-'+month+'-'+day, false, true);
    
}


/**
 * Init voor functionaliteit in avatar selectie
 */


function initHeaderSelect(){
    $('.header_to_select').click(
        function(){
            $('.header_to_select').removeClass("active_img");
            $(this).addClass("active_img");    
            $('#selected_banner').val($(this).attr('id'));
            $('#selected_header_image').attr('src',$(this).find('img').attr('src'));
            $('#selected_header_image').attr('src',$(this).find('img').attr('src'));
            
            
            
            
        });
        $('#save_header').click(
        function(){
           // $('#active_avatar_image').attr('src',$('#selected_avatar_image').attr('src'));
            
            
            //console.log($('#selected_avatar_image').attr('src'));
            
            //alert('change');
            setTimeout('$.modal.close()',1000);
            $('#active_avatar_image').attr('src',$('#selected_avatar_image').attr('src'));
            //return false;
            
            
        });
        
        
}

function busy(element) {
	if (!element) element = '#mid';
	$(element).append('<div class="shade">Even geduld AUB...</div>');
	$('.shade').height($(element).height());
}

function initSlider(id,input,func) {
    $("#"+id).slider({
			'step': 1,
			'min': 0, 
			'max': 100,
			'value': 50,
			'slide': function(e, ui){ 
				$('#'+input).val(ui.value);
			},
			'change': function(){
			    
                if(func) setTimeout(func+'("'+input+'");',1);			    
			}
		});

}



// allow only numbers
function isInt(el, evt) {
	var charCode = ( evt.which ) ? evt.which : event.keyCode;
	return (charCode == 8 || (charCode >= 48 && charCode <= 57));
}

// allow only numbers, a dot and a comma
function isNumeric(el, evt) {
	var charCode = ( evt.which ) ? evt.which : event.keyCode;
	return (charCode == 44 || charCode == 46 || charCode == 8 || (charCode >= 48 && charCode <= 57));
}

var offer = {

	// some variables
	isInit : false,
	itemWidth : 98,
	shiftWidth : 0,
	el : null,
	steps : 0,
	currentStep : 0,
	
	
	// init function to set things up
	init : function(items) {
		
		if(items > 6) {
		    offer.steps = Math.floor(items / 6);
		}
		else {
			offer.steps = 0;
		}
		offer.el = document.getElementById('offerbox_content');
		offer.shiftWidth = offer.itemWidth * 6;
		offer.isInit = true;
	},


	// show next 7 items if we have them
	next : function(items) {
		if(!offer.isInit) offer.init(items);
		if(offer.steps > offer.currentStep) {
			$.get('/company/log-offer-click', {'offer':'','click':'rechts'});
			
			offer.currentStep++;
			offer._shift();
			
		}
	},
	
	
	// show previous 7 items if they are out there
	prev : function() {
		if(!offer.isInit)
			return;

		if(offer.currentStep > 0) {
			$.get('/company/log-offer-click', {'offer':'','click':'links'});
			
			offer.currentStep--;
			offer._shift();
		}
	},
	
	
	// do the actual shifting
	_shift : function() {
		offer.el.style.left = (offer.currentStep * offer.shiftWidth * -1).toString() + 'px';
	}
};

function printShoppinglist()
{
	$.post('/shoppinglist/printerversion?click=boodschappenlijst-print');
	print();
}

function initPlanner() {
    $("div.slidebox").each(function(){
        $(this).find('ul').css({width: '10000px'});
        var left  = $(this).find('.left');
        var right = $(this).find('.right');
        var mid   = $(this).find('.mid');
        
        mid.serialScroll({
            items: 'li',
            prev: left,
            next: right,
            step: 4,
            axis: 'x',
            start: 0, 
            duration:600,
            force:true,
            stop:true,
            lock: true,
            cycle: false, 
            easing:'easeOutQuart',
            jump: false 
        });
        
    });
    
    $('.profile').click(function(){
        var profile_id = $(this).attr("itemid");
        if ($(this).hasClass('selected')) {
            $('input[name=profile_id]').val('');
            $('.profile').removeClass('selected');
        } else {
            $('input[name=profile_id]').val(profile_id);
            $('.profile').removeClass('selected');
            $(this).addClass('selected');
        }
        $('form#plan.ajax').submit();
    });

    $('.platetype').click(function(){
        var platetype_id = $(this).attr("itemid");
        if ($(this).hasClass('selected')) {
            $('input[name=platetype_id]').val('');
            $('.platetype').removeClass('selected');
        } else {
            $('input[name=platetype_id]').val(platetype_id);
            $('.platetype').removeClass('selected');
            $(this).addClass('selected');
        }   
        $('form#plan.ajax').submit();
    });
    
}


// Logging
$(function() {
	var tips = $('#companiesTips');
	var plaats = $('#plaatsValue', tips).html();
	
	var offers = $('.offer', tips);
	var contextMenus = $('.tipsMenu', tips);
	
	offers.each(function(index) {
		var offer = $(this);
		
		var log = function(optie) {
			var itemId = offer.attr('itemid');
			$.get('/company/log-tips-click', {'plaats':plaats,'optie':optie,'itemid':itemId});
		}

		offer.bind('mousedown', function() {
			log('klik');
		});
		$('.moreInfo', contextMenus[index]).bind('mousedown', function() {
			log('meer info');
		});
		$('.zoekGerecht', contextMenus[index]).bind('mousedown', function() {
			log('zoek gerecht');
		});
		$('.plaatsBoodschappenlijst', contextMenus[index]).bind('mousedown', function() {
			log('op boodschappenlijst');
		});
	});
});

$(function() {
	$('.fileUploadPreview').each(function() {
		var tmp = $(document.createElement('div'));
		$(document).append(tmp);
		var preview = $('.preview', this);
		var toggle  = $('.delete', preview);
		var upload  = $('.upload', this);
		var cancel  = $('.cancel', upload);
		upload.remove();
		toggle.bind('click', function(event) {
			event.preventDefault();
			preview.after(upload);
			tmp.append(preview);
		});
		cancel.bind('click', function(event) {
			event.preventDefault();
			upload.after(upload);
			tmp.append(upload);
		});
	});
});

function bannerClick(banner) {
	ajax_load('/index/banner-click?banner='+banner, null, true);
}
