window.kortingstafel = window.kortingstafel || {};
kortingstafel.listing = kortingstafel.listing || {};

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
};


function makeFavorite(node) {
	var ping = new Image();
	ping.src = node.href;
	$('span', node)[0].innerHTML = 'Favoriet';
	$('span', node)[0].className = 'fav';
	return false;
}


kortingstafel.photoCarouselInit = function() {
	$('.photos > .photo').fadeOut().parent().find(':nth-child(1)').fadeIn();
	
	$('.photos > .photo > .previous-photo').click(function() {
		console.log('click previous');
		var oPhoto = $(this.parentNode);
		var oContainer = oPhoto.parentNode;
		var aPhotos = $('.photo', oContainer);
		var iIndex = aPhotos.index(oPhoto);
		var oPrevious = aPhotos.eq(iIndex - 1);
		if(oPrevious) {
			oPhoto.fadeOut('slow','easeInCirc', function() {
				oPrevious.fadeIn('slow', 'easeInCirc');
			});
		}
	});
	
	$('.photos > .photo > .next-photo').click(function() {
		console.log('click next');
		var oPhoto = $(this.parentNode);
		var oContainer = oPhoto.parentNode;
		var aPhotos = $('.photo', oContainer);
		var iIndex = aPhotos.index(oPhoto);
		var oNext = aPhotos.length - 1 == iIndex ? oPhoto : aPhotos.eq(iIndex + 1);
		if(oNext && oNext !== oPhoto) {
			oPhoto.fadeOut('slow','easeInCirc', function() {
				oNext.fadeIn('slow', 'easeInCirc');
			});
		}
	});	
};


kortingstafel.profileViewHandler = function() {
	odd = function() {
		var $self = $(this);
		var $parent = $self.closest(".tab");
		var $menu = $(".profile-menu", $parent);
		console.log($parent.height());
		$menu.fadeIn();
		$parent.animate({height: $parent.height() + $menu.height()});
		console.log($menu.height());
	};
	
	even = function() {
		var $self = $(this);
		var $parent = $self.closest(".tab");
		var $menu = $(".profile-menu", $parent);
		$menu.fadeOut();
		console.log($parent.height());
		$parent.animate({height: $parent.height() - $menu.height()});
		console.log($menu.height());
	};
	
	$(".view-profile-menu").toggle(odd, even);
};


kortingstafel.citySelectorHandler = function() {
	$('.city-chooser-button').click(function() {
		var oCityWrapper = $('#city-wrapper');
		oCityWrapper.slideToggle('fast');
	});
}


kortingstafel.cascadeWidgetHandler = function() {
	var oWidgets = $('.widget');
	for(i=0; i<=oWidgets.length; i++) {
		var oWidget = $(oWidgets[i]);
		oWidget.delay(i*100).slideDown('easing', 'easeInCirc').animate();
	}
}


kortingstafel.formSubmissionHandler = function() {
	$('.standard-form').submit(function() {
		$('.submit-button', this).empty();
		$('.submit-button', this).text(gettext('Just a second...'));
	});
	
	$('.standard-form .submit').click(function() {
		$(this).closest('.standard-form').submit();
	});
	$("form").live('keypress', function(e) {
		if(e.keyCode && e.keyCode == 13) {
			$(this).closest('.standard-form').submit();
		}
	});}


kortingstafel.datePickerHandler = function() {
	if($.fn.datepicker)
		$('.datepicker').datepicker();
}

$(document).ready(function() {
	
	kortingstafel.photoCarouselInit();
	kortingstafel.profileViewHandler();
	kortingstafel.citySelectorHandler();
	kortingstafel.cascadeWidgetHandler();
	kortingstafel.formSubmissionHandler();
	kortingstafel.datePickerHandler();
	//kortingstafel.listing.handleSearch();
});

























// $('.tables > .table').hide().parent().find(':nth-child(1)').show();

// $('.table .earlier').click(function() {
//     var oTable = $(this).closest('.table');
//     var oParent = oTable.closest('.tables');
//     var aTables = $('.table', oParent);
//     var iIndex = aTables.index(oTable);
//     var oEarlier = aTables.eq(iIndex - 1);
//     if(oEarlier) {
//         aTables.hide();
//         oEarlier.show();
//     }
// });

// $('.table .later').click(function() {
//     var oTable = $(this).closest('.table');
//     var oParent = oTable.closest('.tables');
//     var aTables = $('.table', oParent);
//     var iIndex = aTables.index(oTable);
//     var oLater = aTables.length - 1 == iIndex ? oTable : aTables.eq(iIndex + 1);
//     if(oLater && oLater !== oTable) {
//         aTables.hide();
//         oLater.show();
//     }
// });


//Restaurant detail page
// formRestaurantDetails(0);
// $("div.left a.link").each(function(index) {
//     $(this).click(function() {
//         formRestaurantDetails(index);
//     });
// });

// // Remove comment and upgrade to checklist
// $('select[multiple=multiple]').parent().contents().remove(':not(select)');
// $('select[multiple=multiple]').dropdownchecklist({
//     width: 250
// });

// // Datepicker
// $('.datepicker').datepicker();

// Fix Multiple submit event bug
// $('form').submit(function() {
//     $('.submit-button', this).empty();
//     $('.submit-button', this).text('Een ogenblik geduld...');
// });

// $(function() {
//     $('#gallery a').lightBox();
// });


kortingstafel.listing.handleSearch = function() {
	//Search form
    if ($("select#search_type").val() == 1) {
        $("select#search_discount").hide();
        $("select#search_time").hide();
    }
    else {
        $("select#search_discount").show();
        $("select#search_time").show();
    }
    $("select#search_type").change(function() {
        this.value == 1 ? $("select#search_discount").hide() : $("select#search_discount").show();
        this.value == 1 ? $("select#search_time").hide() : $("select#search_time").show();
    });

    //Search results
    initializeSearchList();
    initializeFormTimeList();
    initializeLogin();
};

function initializeSearchList()
 {
    $('#input-place').attr('emptyvalue', 'zoek op plaats');
    $('#input-name').attr('emptyvalue', 'restaurantnaam');

    $('#search-form').submit(function() {
        $('#input-place, #input-name').each(function() {
            if (this.value == $(this).attr('emptyvalue'))
            this.value = '';
        });
    });

    $('#input-place, #input-name').focus(function() {
        if (this.value == $(this).attr('emptyvalue'))
        this.value = '';
    });

    $('#input-place, #input-name').blur(function() {
        if (this.value.trim() == '')
        this.value = $(this).attr('emptyvalue');
    });

    $('#search-form .search-button').click(function() {
        $('#search-form').submit();
    });

    $('#search-form .search-button input').css({
        'background-color': 'transparent',
        'border': '1px solid transparent',
        'cursor': 'pointer'
    });
    $('#search-form .search-button input').attr('value', '');
}

function initializeLogin()
 {
    $('#login-form .login-button').click(function() {
        $('#login-form').submit();
    });

    $('#login-form .login-button input').css({
        'background-color': 'transparent',
        'border': '1px solid transparent',
        'cursor': 'pointer'
    });
    $('#login-form .login-button input').attr('value', '');
}

function initializeFormTimeList()
 {
    $("table#all-restaurants tr.discount-start").each(function(iIndex) {
        var aRows = $(this).nextUntil('tr.discount-end');

        $('a.time-later', aRows).click(function() {
            aRows.hide();
            $(this).parent().parent().next('tr').show();
        });

        $('a.time-earlier', aRows).click(function() {
            aRows.hide();
            $(this).parent().parent().prev('tr').show();
        });

        aRows.first().find('a.time-earlier').css('visibility', 'hidden');
        aRows.last().find('a.time-later').css('visibility', 'hidden');


        aRows.not('tr:first').hide();
    });
}


function formRestaurantDetails(index)
 {
    $("div.left a.link").removeClass('link-selected');
    $("div.left a.link").eq(index).addClass('link-selected');

    var tabs = $(".middle div.tab").hide();
    $(tabs[index]).show();
}


// kortingstafel.listing = kortingstafel.listing || {
//     portal: {
//         init: function() {
//             var oPortal = this;
//             var oWidgets = $('.widget', oPortal);
//             for (var i = 0; i <= oWidgets.length; i++) {
//                 var oWidget = $(oWidgets[i]);
//                 oWidgets[i] = $('<section/>').insertBefore(oWidget);
//                 oWidgets[i].attr('href', oWidget.attr('href'));
//                 $.extend(oWidgets[i], kortingstafel.listing.widget).init();
//             };
//         }
//     },
//     widget: {
//         init: function() {
//             this.showContent();
//         },
//         loadAjax: function() {
//             var oWidget = this;
//             var oOptions = oOptions || {};
//             oWidget.addClass('loading');
//             oOptions['url'] = oWidget.attr('href');
//             oOptions['complete'] = function(data){
//                 oWidget.showContent(data.responseText);
//                 oWidget.removeClass('loading');
//             };
//             setTimeout(function() {
//                 // timeout needed to show loading gif ? weird bug.
//                 $.ajax(oOptions);
//             }, 100);
//         },
//         showContent: function(html) {
//             var oWidget = this;
//             oWidget.slideUp(0);
//             if (html) {
//                 oWidget.html(html);	
//             }
//             oWidget.animate({'height':'toggle'}, 800, 'easeOutBounce');
//         }
//     }
// };


