/*if(!window.console) {
  window.console = new function() {
    this.log = function(str) {};
    this.dir = function(str) {};
	this.time = function(str) {};
	this.timeEnd = function(str) {};
  };
}
console.log();
*/

var product_ids = [];
var clearproducts_timeout = false;



function fix_cart_for_window()
{
	var current_top = parseInt($('.restaurant #cart').css('top'));
	var new_top = current_top;
	var scrolling = true;

	var minimum_top = 170;
	var zipcode_space = 0;

	if (!($('#restaurant').is('*'))) {
		zipcode_space = 0;
	}

	if ($('.restaurant #cart').height() > $(window).height()) {
		scrolling = false;

		new_top = 1 * (minimum_top+zipcode_space - $(document).scrollTop());
	}
	else {
		if ($(document).scrollTop() > minimum_top) {
			new_top = zipcode_space;
		}
		else {
			new_top = 1 * (minimum_top+zipcode_space - $(document).scrollTop());
		}
	}

	new_top = Math.round(new_top);
	if (new_top != current_top) {
		new_top_px = new_top + 'px';
		$('.restaurant #cart').css('top',new_top_px);
	}

	if (!scrolling) {
		if ($(document).scrollTop() > $('.restaurant #cart').outerHeight()+170) {
			$('.restaurant #cart_reminder').css('display', 'block');
		}
		else {
			$('.restaurant #cart_reminder').css('display', 'none');
		}
	}
	else {
		$('.restaurant #cart_reminder').css('display', 'none');
	}
}

function fix_product_options(el)
{
	var pa = $(el).parent().next();
	var max_width, max_height;
	var min_width, min_height;

	max_width = max_height = 0;
	min_width = min_height = 1000;

	$('a.option-select', pa).each(function(){
		var w = $(this).width();
		var h = $(this).height();
		if (w < min_width) {
			min_width = w;
		}
		if (w > max_width) {
			max_width = w;
		}
		if (h > max_height) {
			max_height = h;
		}
		if (h < min_height) {
			min_height = h;
		}
	});

	max_width += 2;

	if ((max_width != min_width) || (max_height != min_height)) {
		$('a.option-select', pa).css('width', max_width).css('height', max_height);
	}

	return false;
}

function ajax_cart_href(tag)
{
	$.ajax({
		type: 'GET',
		url: $(tag).attr('href'),
		success: function(msg){
			$('div#cart').html(msg);

			$('a.cart_href').click(function(){
				return ajax_cart_href($(this));
			});
			
			if (initMenu() == true) {
				// force a reload if cart is now empty
				window.location = window.location.href;
			}
		}
	});

	return false;
}

function initMenu()
{
	initMenu2();
}

function clearProducts()
{
	//console.time('clearing other counters');

	$('.menucategory li.product').each(function(){
		id = $(this).attr('id');
		have = false;
		for(i=0; i < product_ids.length; i++) {
			if (product_ids[i] == id) {
				have = true;
			}
		}

		if (have) {
			//console.log('ignore ' + id);
		}
		else {
			$(this).removeClass('ordered');
			$('span.productorders',this).replaceHtml('&#160;');
		}
	});

	//console.timeEnd('clearing other counters');
}

function initMenu2()
{
	product_ids = [];

	//console.time('setting counter right first time');

	is_empty = true;
	counter = 0;
	$('div#cart:first div.order tr').each(function(i) {
		id = $(this).attr('rel');
		$('#'+id).addClass('ordered');
		
		val = new String($('.cart-product-count',this).text()).match("[0-9]+");
		count = 1;
		if (val != null) {
			count = parseInt(val);
		} 
	    
		currentval = new String($('#'+id+' .productorders:first',this).text()).match("[0-9]+");
		
		current = 0;
		if (currentval != null) {
			current = parseInt(currentval);
		}
		
		$('#'+id).find('.productorders:first').text(count+current);

		is_empty = false;
		counter++;

		if ((count+current) > 0) {
			product_ids[product_ids.length] = id;
		}
	});
	//console.timeEnd('setting counter right first time');

	//console.log(product_ids);

	if (clearproducts_timeout != false) {
		clearTimeout(clearproducts_timeout);
		clearproducts_timeout = false;
	}
	clearproducts_timeout = setTimeout('clearProducts()', 200);

	$('#ordertotalamount_reminder').text($('#ordertotalamount').text());

	fix_cart_for_window();

	return is_empty;
}

function initMenu1()
{
	clearMenu();

	is_empty = true;
	var counter= 1;
	$('div#cart:first div.order tr').each(function(i) {
		id = $(this).attr('rel');
		$('#'+id).addClass('ordered');
		
		val = new String($('.cart-product-count',$(this)).text()).match("[0-9]+");
		count = 1;
		if (val != null) {
			count = parseInt(val);
		} 
	    
		currentval = new String($('#'+id+' .productorders:first').text()).match("[0-9]+");
		
		current = 0;
		if (currentval != null) {
			current = parseInt(currentval);
		}
		
		$('#'+id).find('.productorders:first').text(count+current);

		is_empty = false;
		counter++;
	});

	return is_empty;
}


function clearMenu()
{
	$('.menucategory li.product').removeClass('ordered');
	$('.menucategory li.product span.productorders').replaceHtml("&nbsp;");
	
}

$.fn.replaceHtml = function( val ) {
    var stack = [];
    return this.each( function(i, el) {
	var oldEl = el;

	oldEl.innerHTML = val;
	return oldEl;

	stack.push( newEl );
    }).pushStack( stack );
};

/**
 * Simpele 'stopwatch' functie om in IE dingen te timen..
 * stopwatch('begin');
 * stopwatch('begin');
 * alert('log');
 */ 
var time = new Date();
var start = time.getUTCSeconds()*1000 + time.getUTCMilliseconds();
var log = "";

function stopwatch(str) {
	var nutime = new Date();
	var nu = nutime.getUTCSeconds()*1000 + nutime.getUTCMilliseconds();
	log += str + ": " + (nu-start)/1000 + "\n";
}


jQuery(function($) {
	var markerhtml = "";


	/*------------------ HOMEPAGE + SEARCH ---------------------------*/

	/* Fading of the examples for smartsearch */
	$('span#smartsearch_examplelist').innerfade({
		animationtype: 'fade',
		speed: 750,
		timeout: 4000,
		type: 'sequence'
	});

	$('div#banner-nieuwe-restaurants').innerfade({
		animationtype: 'fade',
		speed: 750,
		timeout: 4000,
		type: 'sequence',
		'containerheight': 60
	});

	$('#smartsearch a#advancedsearch_link').click( function() {
		$('.smartsearch h1').slideUp();
		$('p.message').slideUp();
		$('form#smartsearch').slideUp();
		$('div#advancedsearch').slideDown();
		return false;
	});

	$('div#advancedsearch a#closeadvanced').click( function() {
		$('div#advancedsearch').slideUp("fast");
		$('p.message').slideDown();
		$('div#searchresultsinfo').slideDown("fast");
		$('.smartsearch h1').slideDown();
		$('form#smartsearch').slideDown();
		return false;
	});

	$('div#advancedsearch a.subsegment_button').toggle(function() {
		$(this).addClass('active');
		$('#choose_subsegment option[value="'+$(this).attr('rel')+'"]').attr('selected', 'selected');
		},
	function() {
		$(this).removeClass('active');
	});

	$('a.submit_adv_search').click( function() {
		$('#advanced_q').attr('value','');
		$('#takeawaydelivery select option[value="'+$(this).attr('rel')+'"]').attr('selected','selected');

		if($("#postcode").attr('value') != "") {
			$('#advanced_q').attr('value', $('#advanced_q').attr('value')+' '+$("#postcode").attr('value') );
		}

		$("#choose_subsegment option").each(function(i) {
			if($(this).attr('selected')) {
				$('#advanced_q').attr('value', $('#advanced_q').attr('value')+' '+$(this).text());
			}
		});

		name_t_or_d = $('#takeawaydelivery select option[value="'+$(this).attr('rel')+'"]').text();

		//$('#advanced_q').attr('value', $('#advanced_q').attr('value')+' '+$(this).attr('rel') );
		$('#advanced_q').attr('value', $('#advanced_q').attr('value')+' '+name_t_or_d);

		$('#searchform').submit();
	});

	/*------------------ SEARCHRESULTS ---------------------------*/

	/* Extra info on the Searchresults page */
	$('a.moreinfo').toggle(
		function() {
			$(this)
				.closest('li')
				.find('.restaurant_extrainfo')
				.slideDown(
					"normal",
					function() {
						$(this).closest('li').find('.restaurantfoto').fadeIn();
					})
				;
			$(this).text('minder info');
			return false;
		},
		function() {
			var li = $(this).closest('li');

			$(li)
				.find('.restaurantfoto')
				.fadeOut(
					"normal",
					function() {
						$(this).closest('li').find('.restaurant_extrainfo').slideUp();
					})
				;
			$(li)
				.find('.restaurant_extrainfo')
				.slideUp()
				;
			//$(this).closest('li').find('.restaurant_extrainfo').slideUp();
			$(this).text('meer info');
			return false;
		}
	);

	/* Edit searchterms on the Searchresults page */
	$('a#edit_searchterms').click( function() {
		if($('div#advancedsearch').css('display') == "none") {
			$('div#searchresultsinfo').slideUp();
			$('div#advancedsearch').slideDown("fast");
			return false;    
		} else {
			$('div#searchresultsinfo').slideDown();
			$('div#advancedsearch').slideUp("fast");
			return false;
		}
	});
	/*---------------- SINGLE RESTAURANT -------------------------*/
	
        $('sub.productdescription span[title]').hovertip();



	/*------------------ MENU AND CART ---------------------------*/

	/* Open and close the productadditions (menupage) */
	$('span.productadditions_link').click( function() { // was: $('span.productadditions_link a')
		if ($(this).hasClass('active')) {
			$(this).closest('li').find('ul.productadditions').slideUp();
			$(this).removeClass('active');
			return false;
		} else {
			$(this).closest('li').find('ul.productadditions').slideDown();
			//.css('display','block')
			$(this).addClass('active');

			fix_product_options(this);

			return false;
		}
	});

	$('a.option-select').click( function(){
		if($(this).hasClass('selected')) {
			$(this).removeClass('selected');
			$(this).closest('li').find('input.select').val('');
			return false;
		} else {
			$(this).parent().find('a').removeClass('selected');
			$(this).addClass('selected');
			$(this).closest('li').find('input.select').val($(this).attr('rel'));
			return false;
		}
	});

	$('a.product-addition-link').click( function(){ // was: $('span.product-addition-check a')
		if($(this).closest('li').find('input.check').attr('checked')) {
			$(this).removeClass('active');
			$(this).closest('li').find('input.check').attr('checked','');
			return false;
		} else {
			$(this).addClass('active');
			$(this).closest('li').find('input.check').attr('checked','checked');
			return false;
		}
	});

	/* Scrolling cart */
	leftpos = ( $("body").width() - 970 ) / 2; 
	$('.restaurant #cart').css('right',1*(leftpos+20)+"px");
	$('.restaurant #cart_reminder').css('right',1*(leftpos+20)+"px");

	if($(window).scrollTop() > 170){
		$('.restaurant #cart').css('top','0px');
	}
	
	if ($.browser.msie) {
		$('.restaurant #cart').show();
	} else {
		$('.restaurant #cart').fadeIn();
	}
	
	$(window).resize( function() {
		//console.log('RESIZE: window.height = ' + $(window).height() + ', cart.height = ' + $('#cart').height());

		if (($(window).width()-970) >= 0) {
			rightoffset = (($(window).width()-970)/2)+20;
		}
		else {
			rightoffset = ($(window).width()-970)+20;
		}
		$('.restaurant #cart').css('right',rightoffset+"px");
		$('.restaurant #cart_reminder').css('right',rightoffset+"px");

		fix_cart_for_window();
	});

	$(window).scroll( function() {
		//console.log('SCROLL: window.height = ' + $(window).height() + ', cart.height = ' + $('#cart').height());

		fix_cart_for_window();
	});
	
	/* Add product to 'cart' */
	$('span.product_add').click(function(){
		vals = $(this).closest('form').serialize();

		$(this).closest('li.product').find('input[name=id]').attr('checked','checked');
		$(this).closest('li.product').addClass('ordered');
		$(this).closest('li.product').find('a').removeClass('active').removeClass('selected');
		$(this).closest('li.product').find('input.check').attr('checked','');
		$(this).closest('li.product').find('ul.productadditions').slideUp();
		//initMenu();
		$.ajax({
			type: "GET",
			url: $(this).closest('form').attr('action'),
			data: vals,
			success: function(msg){
				$('div#cart').html(msg);
				$('a.cart_href').click(function(){
					return ajax_cart_href($(this));
				});
				initMenu();
			}
		});
		return false;
	});

	/* Remove product from 'cart' */
	$('a.cart_href').click(function(){
		return ajax_cart_href($(this));
	});

	$('a#openorder_link').toggle(
		function(){
			$('#cart').fadeIn();
		},
		function() {
			$('#cart').fadeOut();
	});

	// mental to this at all (only one id should ever be found), but ok let's call it growing pains)
	$('div.cart_order').each(function(){
        var height = $(this).outerHeight()-18;
        if ($('div.restaurantdetails',this).parent().attr('id') == 'cart_order') {
            var other_height = $('div.restaurantdetails',this).parent().outerHeight() - 21;

            if (other_height < height) {
                height = other_height;
            }
        }
		$('div.restaurantdetails',this).css('height',height);
	});

	$('a.enter_zipcode').click(function(){
		$('.zipcode_statement').hide();
		$('.zipcode_form').show();
        $('#zipcode_focus').focus();
		return false;
	});
	$('a.view_zipcode').click(function(){
		$('.zipcode_form').hide();
		$('.zipcode_statement').show();
		return false;
	});

	initMenu();
	
	/* Rounded Corners in IE and Opera */
	//if ((($.browser.msie === true || $.browser.opera === true)) && (false)) {
	if ($.browser.opera === true) {
		DD_roundies.addRule('.rounded2', '2px');
		DD_roundies.addRule('.rounded3', '3px');
		DD_roundies.addRule('.rounded4', '4px');
		DD_roundies.addRule('.rounded10', '10px');

		//$("input#smartsearch_input").boxShadow( 0, 0, 20, "#ffd76a" );
	} 
});

