/* No Conflict */
jQuery.noConflict();

/*
 * News
 */
jQuery(function($){
    $('#news li:even').addClass('even');
});

/*
 * Tabs
 */
jQuery(function($){
    $('#tabs').tabs({
    	cookie: true
    });
});

/*
 * Accordion
 */
jQuery(function($){
    $('#searchForm .accordion').accordion({
        autoHeight: false,
        collapsible: true,
        active: false
    });

});

/*
 * Villa Booking
 */
jQuery(function($){

    var $form = $('#villa-book'),
        $cancellation = $('#cancelation'),
		$damageCost = $('#price-preview .damage-cost'),
        $cancellationPrice = $('.cancel-price', $cancellation),
        $accordion = $('.accordion', $form),
        $step1 = $('#step-1 > div'),
        $step1Header = $step1.siblings('a'),
        $step2 = $('#step-2 > div'),
        $step2Header = $step2.siblings('a'),
        $step3 = $('#step-3 > div'),
        $step3Header = $step3.siblings('a'),
        $terms = $('#termsAndConditions'),
        $extraServices = $('#extra-included-services'),
        $extraServicesColRight = $('#extras');

    //Disabling links on accordion headers
    $('>ul>li>a', $form).click(function(){ return false; });

    //Hiding step-2 and step-3 on page load
    $step2.add($step3).hide();

    //Step 1 Next
    $('.next', $step1).click(function(){
        $step1.hide();
        $step3.hide();
        $step2.show();
        return false;
    });

    //Step 1 Header
    $step1Header.click(function(){
        $step2.hide();
        $step3.hide();
        $step1.show();
    });

    //Step 2 Next
    $('.next', $step2).click(function(){
        if ($form.validate().form()) {
            $step3.show();
            $step2.hide();
            $step1.hide();
            $('.guestInitials').trigger('change');
        }
        return false;
    });

    //Step 2 Previous
    $('.prev', $step2).click(function(){

            $step1.show();
            $step2.hide();
            $step3.hide();

        return false;
    });

    //Step 2 Header
    $step2Header.click(function(){
        $('.next', $step1).trigger('click');
    });

    //Step 3 Next
    $('.next', $step3).click(function(){
        if (!$terms.is(':checked')) {
            $('<label class="error">'+ $.validator.messages.required +'</label>').appendTo($terms.parent());
            return false;
        }
    });

    //Step 3 Previous
    $('.prev', $step3).click(function(){

            $step2.show();
            $step1.hide();
            $step3.hide();

        return false;
    });

    //Step 3 Header
    $step3Header.click(function(){
        $('.next', $step2).trigger('click');
    });


    /*
     * Calculating Totals
     */
    var $total = $('#total'),
        total = parseFloat($total.text().replace(' ','').replace('.','').replace(',','.')),
        $changeEl = $('#accordion-content :checkbox, #cancellation :radio', $form),
        $otherGuests = $('#other-guests');

    /* When Changeing Guests info, recalculate the Prices for Linen */
    $otherGuests.bind('change blur', function(){
    	$changeEl.trigger('change');
    });

    /* Adding to the total + cancellation */
    $changeEl.bind('change click', function(event){
        var newTotal = total;
        //Disabling & Enabling of mutual exclusive fields
        var $f1 = $('#local_bedlinen_packet'), $f2 = $('#local_linen_packet');
        if ($(event.target).is('#local_linen_packet')) {
            if ($f2.is(':checked')) { $f1.attr('checked', false); }
            if ($f1.is(':checked')) { $f2.attr('checked', false); }
        } else if ($(event.target).is('#local_bedlinen_packet')) {
            if ($f1.is(':checked')) { $f2.attr('checked', false); }
            if ($f2.is(':checked')) { $f1.attr('checked', false); }
        }


        //Fixed  extra
        $changeEl.filter(':checkbox').each(function(){
            if ($(this).is(':checked')) {
                $(this).val($(this).attr('data-price'));
            } else {
                $(this).val('');
            }
        });
        $changeEl.filter(':checkbox:checked').not('.local').each(function(){
            if ($(this).attr('data-price') != ''){
                newTotal += eval($(this).attr('data-price'));
            }

        });

        //Cancellation fees
//        newTotal += ($changeEl.filter(':radio:checked').attr('data-cancellationtax'))?parseFloat($changeEl.filter(':radio:checked').attr('data-cancellationtax').replace(',','.')):0;
//
//        if (!$changeEl.filter(':radio:checked').attr('data-cancellationtax')) {
//            $cancellation.hide();
//        } else {
//            $cancellation.show();
//            $cancellationPrice.text($changeEl.filter(':radio:checked').attr('data-cancellationtax'));
//        }
//
//        $total.html($.formatNumber(newTotal, {format:"#,###.00", locale:"at"}));

        //Cancellation fees
        newTotal += ($changeEl.filter(':radio:checked').attr('data-cancellationtax'))?parseFloat($changeEl.filter(':radio:checked').attr('data-cancellationtax').replace(',','.')):0;

        if (!$changeEl.filter(':radio:checked').attr('data-cancellationtax')) {
            $cancellation.hide();
			$damageCost.show();
			$total.html($.formatNumber(newTotal, {format:"#,###.00", locale:"at"}));
        } else {
            $cancellation.show();
			if($changeEl.filter(':radio:checked').parent('.shortTermCancelation')[0]){
				$damageCost.hide();
				var minusdamage = $damageCost.children('span').text();
				minusdamage = minusdamage.replace(',','');
				minusdamage = minusdamage.replace('.','');
				var pattern = /[0-9]+/g;
				var minusdamageNo = minusdamage.match(pattern)[0]/100;
				newTotal = newTotal - minusdamageNo;
				$cancellationPrice.text($changeEl.filter(':radio:checked').attr('data-cancellationtax'));
				$total.html($.formatNumber(newTotal, {format:"#,###.00", locale:"at"}));
			} else {
				$damageCost.show();
				$cancellationPrice.text($changeEl.filter(':radio:checked').attr('data-cancellationtax'));
				$total.html($.formatNumber(newTotal, {format:"#,###.00", locale:"at"}));
			}
            //$cancellationPrice.text($changeEl.filter(':radio:checked').attr('data-cancellationtax'));
        }

        //Step 3 / extra services that are selected at step 1
        var extraElements = '',
            extraElementsRightCol = '',
            localBedlinenPrice;

        $changeEl.filter(':checkbox:checked').each(function(){
            var $label = $(this).siblings('label'),
            	priceRaw = $(this).attr('data-price'),
                price = $.formatNumber($(this).attr('data-price').replace(',','.'), {format:"#,###.00", locale:"at"}),
                text = $(this).attr('data-title');

            /* Special Case for Linen */
            if ($(this).is('#direct_linen_packet, #direct_bedlinen_packet, #local_bedlinen_packet, #local_linen_packet')){
		    	var guestNo = $('#step-3 .guest-row').filter(function(){return $.trim($(this).text()) != "";}).length;
		    	if(guestNo!==0){
			    	//Right col price

			    	price = $.formatNumber(priceRaw*(parseInt(guestNo)+1), {format:"#,###.00", locale:"at"});
			    	$('#step-3 .priceValue').html(price);
			    	localBedlinenPrice = price;
				  }
			      newtext = '<div><label>'+text+'</label><span class="price">&euro; '+price+'</span></div>';
            } else {
              newtext = text;
            }

            if($(this).is('.local')) {
                extraElements += newtext;
            }
            if($(this).is('.direct')) {
                extraElementsRightCol += '<div><span>\u20AC '+price+'</span>'+text+'</div>';
            }
        });
        $extraServices.html(extraElements);
        $extraServicesColRight.html(extraElementsRightCol);
        $('#step-3 .priceValue').html(localBedlinenPrice);

    }).trigger('change');


})

/*
 * Datepicker
 */
jQuery(function($) {

    $.datepicker.setDefaults($.datepicker.regional['nl']);

    var $input = $('#start-date'),
        $calendar = $('#start-date-calendar');

    $calendar.datepicker({
        beforeShowDay: function(dt) {
            return [dt.getDay() == 6, ""];
        },
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd-mm-yy',
        yearRange: 'n:1+n',
        defaultDate: $.datepicker.parseDate("d m y", "1 7 2012"),
        //Trigger a change event to trigger the ajax search
        onSelect: function(dateText, inst) {
            $input.val(dateText);
            $input.trigger('change');
        }
    });

});


/*
 * Datepicker Date of Birth (reservation)
 */
jQuery(function($) {

    var $calendar = $('.guestDateOfBirth, .dateOfBirth');

    $calendar.datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true,
        yearRange: '1900:n',
        showOn: "button",
        buttonImage: "fileadmin/images/calendar-icon.gif",
        buttonImageOnly: true,
        onSelect: function(dateText, inst) {
            $('.guestInitials').trigger('change');
        }
    });

});

/*
 * Range Slider
 */
jQuery(function($){
    var $min = $('#price-min'),
        $max = $('#price-max'),
        $slider = $('#price-slider');

    $slider.slider({
            range: true,
            min: 1500,
            max: 3500,
            step: 50,
            animate: true,
            values: [ ($min.val())?$min.val():1500, ($max.val())?$max.val():3500 ],
            slide: function( event, ui ) {
                $min.val(ui.values[0]);
                $max.val(ui.values[1]);
            },
            change: function(event, ui) {
                //Trigger a change event on the input to trigger the ajax search
                $min.trigger('change');
            }
        });

});

/*
 * Search Form AJAX
 */
jQuery(function($){

    var $form = $('#searchForm'),
        $form2 = $('#searchFormNumber'),
        $results = $('.results strong'),
        formData = '',
        url = '/index.php?id=42';

    $('input, select', $form).bind('change', function(){

        //Preparing the data
        formData = $form.serialize();

        $results.addClass('loading');

        //AJAX request
        $.ajax({
            url: url,
            method: 'POST',
            data: formData+'&ajaxSearch=1',
            success: function(data){
                $results.text(data).removeClass('loading');
            }
        });

    }).eq(0).trigger('change');

    /*$('input, select', $form2).bind('change', function(){

        //Preparing the data
        formData = $form2.serialize();

        $results.addClass('loading');

        //AJAX request
        $.ajax({
            url: url,
            method: 'POST',
            data: formData+'&ajaxSearch=1',
            success: function(data){
                $results.text(data).removeClass('loading');
            }
        });

    }).eq(0).trigger('change');*/


});


/*
 * Print Link
 */
function PrintLink() {
    var url = document.location.href;
    var newurl = url;
    if ( url.indexOf("?") > -1 ) newurl = newurl+'&typeP=1';
    else  newurl = newurl+'?typeP=1';
    window.open(newurl,'PrintPage','menubar=1,scrollbars=1,width=940,height=680');
}

//Image Gallery
jQuery(function($){

    var $imageGalleryInner = $('.img-gallery-inner');

    //Gallery Scripts
    $.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) {
        $(pager).find('li').removeClass('active')
            .filter('li:eq('+currSlideIndex+')').addClass('active');
    };

    $('.img-gallery-inner').after('<ul class="img-gallery-pager">').cycle({
        fx:     'fade',
        speed: 300,
        pagerEvent: 'mouseenter.pager',
        timeout: 0,
        pager:  '.img-gallery-pager',


        pagerAnchorBuilder: function(idx, slide) {
            img = slide.getElementsByTagName('img')[0];
            return (img)?'<li><a href="#"><img src="'+img.src+'" width="78" height="58" /></a></li>':'';
        }
    });

    $('.img-gallery-pager a').click(function(){
        $('a:visible', $imageGalleryInner).click();
    });

});

//Fancybox
jQuery(function($){

    $('.img-gallery-inner a').attr('rel','gallery-1').fancybox();

});

//Foto Gallery Switch Link
jQuery(function($){

    $('.img-more a').click(function(){
        $('.tab-2 a').click();
    });

});

//Animate Table
jQuery(function($){

    var $slider = $('#slider-inner'),
        step = parseInt($('.price-col').width()),
        $sliderWidth = parseInt($slider.find('.price-col').size())*step,
        sliderMax = $sliderWidth-(step*3),
        $prev = $('#price-prev'),
        $sliderLeft = $slider.css('left'),
        $sliderPos = parseInt($sliderLeft, 10);

    $slider.css('left','0').css('width',$sliderWidth);

    if( $sliderPos == 0 ) { $prev.hide(); } else { $prev.show(); }

    $('#price-prev').click(function(){

        var $left = $slider.css('left');
        var $nLeft = parseInt($left, 10);
        if ($nLeft < 0 && !$slider.is(':animated')){
            $slider.animate({
                left: '+=56'
            }, 500,function(){
                var $left = $slider.css('left');
                var $nLeft = parseInt($left, 10);
                if( -$nLeft <= 0 ) { $('#price-prev').hide(); } else { $('#price-prev').show(); }
                if( -$nLeft >= sliderMax ) { $('#price-next').hide(); } else { $('#price-next').show(); }
            });

        }

        return false;
    });


    $('#price-next').click(function(){
        var $left = $slider.css('left');
        var $nLeft = parseInt($left, 10);
        if ($nLeft <= 0 && !$slider.is(':animated')){
            $slider.animate({
                left: '-=56'
            }, function(){
                var $left = $slider.css('left');
                var $nLeft = parseInt($left, 10);
                if( -$nLeft <= 0 ) { $('#price-prev').hide(); } else { $('#price-prev').show(); }
                if( -$nLeft >= sliderMax ) { $('#price-next').hide(); } else { $('#price-next').show(); }
            });
        }

        if ($nLeft == -sliderMax)
            $slider.stop();
        return false;
    });



    //Hide Browse when Less than 3
    if($slider.find('.price-col').size() <= 3)
    $('#price-prev, #price-next').hide();

    //Datepicker
    var $calendar = $('#calendar'),
        $dateWrapper = $('.cell-top', $slider);

    $calendar.datepicker({
        beforeShowDay: function(dt) {
            return [dt.getDay() == 6];
        },
        onSelect: function(dateText, inst) { //scroll the selected date into view
            setCalendar(dateText);
        },
        changeMonth: true,
        changeYear: true,
        yearRange: 'n:1+n',
        dateFormat: 'dd/mm/y',
        showOn: 'both',
        buttonImage: "fileadmin/images/calendar-icon.gif",
        buttonImageOnly: true,
        minDate: 0

    });

    function setCalendar(dateText){
        //find the date in the table
        var scrollTo = 0,
            found = false;
        $dateWrapper.each(function(index){
            var $el = $(this),
                $left = $slider.css('left'),
                $nLeft = parseInt($left, 10),
                i = index;

            if ($el.text().indexOf(dateText) > 0) {
                found = true;
                $newLeft = i*56;
                $slider.animate({
                    left: -$newLeft
                },500, function(){
                    var $left = $slider.css('left');
                    var $nLeft = parseInt($left, 10);
                    if( -$nLeft <= 0 ) { $('#price-prev').hide(); } else { $('#price-prev').show(); }
                    if( -$nLeft >= sliderMax ) { $('#price-next').hide(); } else { $('#price-next').show(); }
                });
            }
        });

        //Going to the last item if the date searched is not found, and setting a NA status on the selected date
        if (!found) {
            var $lastItem = $dateWrapper.filter(':last'),
                $lastItemDate = $('.col-date', $lastItem);
            $newLeft = ($dateWrapper.length-1)*56;
            $lastItemDate.text(dateText);
            $slider.animate({
                    left: -$newLeft
                    },500, function(){
                        var $left = $slider.css('left');
                        var $nLeft = parseInt($left, 10);
                        if( -$nLeft <= 0 ) { $('#price-prev').hide(); } else { $('#price-prev').show(); }
                        if( -$nLeft >= sliderMax ) { $('#price-next').hide(); } else { $('#price-next').show(); }
                    });
        }
    }

    if ($calendar.val() != '') setCalendar($calendar.val());

});

//Filters Display
//check the source in ext_displaySearch.html


/*
 * Go to booking
 */
jQuery(function($){
    $('#blue-box .reserve-button').click(function(){
        return $(this).is('.active');
    });
});


/*
 * Step 3 personal data
 */
jQuery(function($){

    var $personalData = $('#personal-data'),
        $fields = $('#initials, #firstName, #surname, #street, #number, #zip, #city, #country, #phone, #mobile, #email'),

        $guests = $('#other-guests'),
        $guestLabels = $('label', $guests),
        $allGuestFields = $('select, input', $guests),
        $guestRow = $('.guest-row', $guests),
        $guestData = $('#guest-data');

    $fields.bind('change blur keyup', function(){
        $personalData.empty();
        $fields.each(function(){

            var $el = $(this),
                label = $(this).siblings('label').not('.error').text(),
                value = $el.val();
            if (value != '') $('<div><label>'+label+'</label>'+value+'</div>').appendTo($personalData);

        });
    });


    //Attach event when changing something in the Guest fields
    //Recreating all guests
    $allGuestFields.bind('click change keyup', function(){

        var guestContent = '';

        $guestRow.each(function(){
            var $row = $(this),
                $guestFields = $('select, input', $row);

                guestContent += '<div class="guest-row">';
                $guestFields.each(function(i){
                    var value = $(this).val();
                    //Special case for gender
                    if (this.name.indexOf('guestTitle') >= 0) {
                        if ((value != '') && (value != '0') && (value != 0)) guestContent += $('option:selected', this).text()+' ';
                    } else {
                        if ((value != '') && (value != '0') && (value != 0)) guestContent += value+' ';
                    }
                });
                guestContent += '</div>';

        });

        if (guestContent != '') guestContent = '<h2>'+$guests.prev('h2').text()+'</h2>'+guestContent;
        $guestData.html(guestContent);
    });


});


/*
 * Clear Cookie
 */
jQuery(function($){

    $('#reset-filter').click(function(){
    	reset();
    	$.cookie('sword', null, { path: '/' });
    });

    $('#searchFormNumber').bind('submit', function(){
    	reset();
    });


    function reset(){
    	$.cookie('rentalPeriod', null, { path: '/' });
        $.cookie('start_date', null, { path: '/' });
        $.cookie('max_persons', null, { path: '/' });
        $.cookie('pet', null, { path: '/' });
        $.cookie('internet', null, { path: '/' });
        $.cookie('air_conditioning', null, { path: '/' });
        $.cookie('pool', null, { path: '/' });
        $.cookie('pool_heated', null, { path: '/' });
        $.cookie('sea_view', null, { path: '/' });
        $.cookie('bedroom_number', null, { path: '/' });
        $.cookie('sea_distance', null, { path: '/' });
        $.cookie('price_max', null, { path: '/' });
        $.cookie('price_min', null, { path: '/' });

        $.cookie('sword', null, { path: '/' });
        $.cookie('city', null, { path: '/' });
    }

});

/*
 * Villa Search Active Tab
 */
jQuery(function($){
    var $form = $('#searchForm');
    $form.bind('submit', function(){
        if ($('#sword').val() != '') {
            $form.attr('action', $form.attr('action')+'#tab-2');
        }
    });

});

/*
 * Firefox Hack for buttons
 */
jQuery(function($){

    if ($.browser.mozilla)
    {
        $('.accordion .next span').css({ position: 'relative', top: '-1px', right: '-3px' });
        $('.accordion .prev span').css({ position: 'relative', top: '-1px', right: '-3px' });
    }
})

/*
 * qTips
 */
jQuery(function($){
	$('.info').qtip({
	});
});

/*
 * Slideshow
 */
jQuery(function($){
	$('#slideshowRecursive').cycle({
		fx: 'fade'
	});
});


/*
 * SSL PAGES
 */
jQuery(function($){
	var url = location.href;
	var baseURL = url.substring(0, url.indexOf('/', 14));
	var host = baseURL.split('://');

	$('.sslpg #header a, .sslpg #footer a').each (function($) {
		$link = jQuery(this).attr('href');
		jQuery(this).attr('href', 'http://'+host[1]+'/'+$link);
	});
});


jQuery(function($){
	$('.cancelationInfoLink').fancybox({
		type: 'iframe'
	});

});

// on villa single, display discount, if it's the case
jQuery(function($){

	var x= $('#final-price span').attr('price');
	$('#final-price span').html('&euro; ' + x);

});

jQuery(function($){
	$('.cell').each(function(){
			//$(this).wrapInner('<div/>');
			if($(this).find('a').attr('price')){
				$(this).find('a').css('font-weight','bold').css('color','#CE7809');
			    	var x = $(this).find('a').attr('price');
			    	//$(this).children('div').css('position','relative').append('<span class="price" style="display: none; height: 15px; z-index: 1000; position: absolute; left: 3px; bottom: 20px; padding: 0 3px; color: #000; border: solid 1px #ccc; background: #fff; min-width: 90px;">' + x + '</span>');
			    	$(this).css('position','relative').append('<span class="price" style="display: none; z-index: 1000; position: absolute; left: -13px; top: 20px; font-size: 11px; line-height: 12px; padding: 0 3px; color: #000; border: solid 1px #ccc; background: #fff; min-width: 90px;">' + x + '</span>');
			}

		});
	$('.cell').hover(function(){
			$(this).find('span').css('display','block');
		},
		function(){
			$(this).find('span').css('display','none');
		}
	);
});

jQuery(function($){
	if($('#final-price')[0]){}
	else {$('#rent-price').addClass('bordered')}
});
