// Returns URL parameter by name
function getParameterByName(name) {
	var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
	return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

$(document).ready(function () {
    
    /*BOOKING JS FIX*/
    $('#orderInfo .orderFormSubmit').attr('disabled', ''); 

    var lang = $('body').hasClass('DE') ? 'de' : 'dk';

    // Form element styling
    $(".checkbox input, select").uniform();

    // Datepicker - only saturday selectable
    $('.datepicker').datepicker({
        beforeShowDay: function (date) {
            if (date.getDay() != 6) { return [false]; } else { return [true]; };
        },
        numberOfMonths: 1,
        minDate: '-6D',
        maxDate: '+2Y',
        dateFormat: 'dd-mm-yy',
        firstDay: 1
    });

    //Selective Date picker
    var enabledDays; // = ["3-5-2011", "3-12-2011", "3-19-2011", "3-26-2011", "4-2-2011", "4-9-2011", "4-16-2011", "4-30-2011", "5-21-2011", "6-18-2011", "6-25-2011", "7-2-2011", "8-27-2011", "10-1-2011", "10-8-2011", "10-15-2011", "10-22-2011", "10-29-2011", "11-5-2011", "11-12-2011", "11-19-2011", "11-26-2011", "12-3-2011", "12-10-2011", "12-17-2011", "12-24-2011", "12-31-2011", "1-7-2012", "1-14-2012", "1-21-2012", "1-28-2012", "2-4-2012", "2-11-2012", "2-18-2012", "2-25-2012", "3-3-2012", "3-10-2012", "3-17-2012", "3-24-2012", "3-31-2012", "4-7-2012", "4-14-2012", "4-21-2012", "4-28-2012", "5-5-2012", "5-12-2012", "5-19-2012", "5-26-2012", "6-2-2012", "6-9-2012", "6-16-2012", "6-23-2012", "6-30-2012", "7-7-2012", "7-14-2012", "7-21-2012", "7-28-2012", "8-4-2012", "8-11-2012", "8-18-2012", "8-25-2012", "9-1-2012", "9-8-2012", "9-15-2012", "9-22-2012", "9-29-2012", "10-6-2012", "10-13-2012", "10-20-2012", "10-27-2012", "11-3-2012", "11-10-2012", "11-17-2012", "11-24-2012", "12-1-2012", "12-8-2012", "12-15-2012", "12-22-2012", "12-29-2012"];

    if ($('.selDatepicker').length != 0) {

        // OLD - Outcommented 29/06 to remove check on todays date, so that "last saturday" comes out
        //        function enableAllTheseDays(date) {
        //            for (i = 0; i < enabledDays.length; i++) {
        //                var txtDate = (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear();
        //                if ((date > new Date()) && ($.inArray(txtDate, enabledDays) != -1)) {
        //                    return [true];
        //                }
        //            }
        //            return [false];

        // Enable a list of dates
        function enableAllTheseDays(date) {
            for (i = 0; i < enabledDays.length; i++) {
                var txtDate = (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear();
                if (($.inArray(txtDate, enabledDays) != -1)) {
                    return [true];
                }
            }
            return [false];
        }

        $.ajax({ type: "POST",
            url: "/services/dhd.asmx/GetGoodDates",
            data: "{ 'hId': '" + $('.hiddenHouseId').val() + "' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                enabledDays = msg.d;
            }
        });

        //selective datepicker 
        $('.selDatepicker').datepicker({
            dateFormat: 'dd-mm-yy',
            beforeShowDay: enableAllTheseDays,
            firstDay: 1
        });

    }

    // Gallery hack
    if ($("#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusSeHus_9_ulImages").children().size() > 7) {
        $(".moreLink").html("<a href=\"#\">Flere billeder</a>");
        $(".moreLink a").click(function () {

            $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusSeHus_9_ulImages li:eq(7) a').trigger('click');
            return false;
        });
    }
    if ($(".gallery").children().size() > 4) {

        $(".moreLink a").click(function () {

            $('.gallery li:eq(4) a').trigger('click');
            return false;
        });
    }

    // Lightbox popups
    $('#popCancelInsurance').click(function () {
        $('#lightbox_CancelInsurance_' + lang).lightbox_me({ overlayCSS: { opacity: 1 }, centered: true });
        return false;
    });

    // Season calendar
    $('#popupSeasonCalendar').click(function () {
        var tmpl = '<div class="lightbox info large" style="display: none;" id="lightbox_offer"><div class="header">{top}</div><div class="content"><a href="" id="season1" class="selected"></a> | <a href="" id="season2"></a><div id="seasonContent">{content}</div></div><a class="close">{close}</a></div>',
			 top = (lang === 'dk') ? 'Sæsonkalender' : 'Saisonkalender',
			 close = (lang === 'dk') ? 'Luk' : 'Schließen',
			 year = 2011; // Just change this for new seasons, shows year and year+1 (ie 2011 and 2012)
        $.get('/custom/server.aspx', { 'action': 'seasonCal', 'lang': lang, 'year': year + '' }, function (data) {
            var out = template(tmpl, { 'content': data, 'top': top, 'close': close });
            var content = $(out).find('#season1, #season2')
				.html(function (index) { return year + index + ''; })
				.click(function () {

				    $.get('/custom/server.aspx', { 'action': 'seasonCal', 'lang': lang, 'year': $(this).text() }, function (data) {
				        $('#seasonContent').html(data);
				    });

				    //$('#seasonContent').load('/custom/server.aspx', { 'action': 'seasonCal', 'lang': lang, 'year': $(this).text() }); 
				    return false;
				})
				.end();
            content.appendTo('body').lightbox_me({ overlayCSS: { opacity: 1 }, centered: true });
            console.log(content);
        }, 'html');
        return false;
    });

    // Special offer popup
    $('#offerPopup, .offerPopup').click(function () {
        console.log('popup');
        var tmpl = '<div class="lightbox" style="display: none;" id="lightbox_offer"><div class="header">{top}</div><div class="content"><h1>{title}</h1>{content}</div><div class="side"><img src="/ImageGen.ashx?image={image}&width=200&height=160&Constrain=false&Crop=resize" alt="" /></div><a class="close">{close}</a></div>',
			 top = (lang === 'dk') ? 'Specialtilbud' : 'Spezial angebot',
			 close = (lang === 'dk') ? 'Luk' : 'Schließen',
		     id = $(this).attr('data-offerid');
        $.get('/services/Dhd.asmx/GetPopupInfo', { OfferId: id, sprog: (lang === 'dk') ? 'da' : 'de' }, function (data) {
            var title = $(data).find('title').text(),
			     content = $(data).find('content').text(),
				 image = $(data).find('image').text(),
				 out = template(tmpl, { 'title': title, 'content': content, 'image': image, 'top': top, 'close': close });

            $(out).appendTo('body').lightbox_me({ overlayCSS: { opacity: 1 }, centered: true });
        }, 'xml');
        return false;
    });


    //Webcam popups
    $('#webcamPopup1').click(function () {
        //OLD IP 87.62.155.62 - 17-02
        var tmpContent = ''; 
        if ($('html').hasClass('ie7') || $('html').hasClass('ie8') || $('html').hasClass('ie9')) {
            tmpContent = '<iframe src="http:/93.162.163.118/ImageViewer?Resolution=320x240&Quality=Motion&Size=STD&PresetOperation=Move&Data=0&Frame2=PanTilt&Type=&Language=9&RPeriod=0&Sound=Enable" scrolling="no" width="320" height="240" > </iframe>';
        }
        else {
            tmpContent = '<input width="320" type="image" height="240" border="0" src="http://93.162.163.118/nphMotionJpeg?Resolution=320x240&amp;Quality=Motion" name="NewPosition"></input>';
        }
        var tmpl = '<div class="lightbox info webcams" style="display: none;" id="lightbox_offer"><div class="header">Webcam</div><div class="content"><h2>{text}</h2>{content}</div><a class="close">{close}</a></div>',
             text = (lang === 'dk') ? 'Vores kontor' : 'Unser Büro am Ortseingang',
             content = tmpContent,
			 close = (lang === 'dk') ? 'Luk' : 'Schließen',
		     id = $(this).attr('data-house');

        out = template(tmpl, { 'text': text, 'content': content, 'close': close });

        $(out).appendTo('body').lightbox_me({ overlayCSS: { opacity: 1 }, centered: true });

        return false;
    });

    $('#webcamPopup2').click(function () {
        var tmpContent = '';
        if ($('html').hasClass('ie7') || $('html').hasClass('ie8') || $('html').hasClass('ie9')) {
            tmpContent = '<iframe src="http://80.162.132.246/ImageViewer?Resolution=320x240&Quality=Motion&Size=STD&PresetOperation=Move&Data=0&Frame2=PanTilt&Type=&Language=9&RPeriod=0&Sound=Enable" scrolling="no" width="320" height="240" > </iframe>';
        }
        else {
            tmpContent = '<input width="320" type="image" height="240" border="0" src="http://80.162.132.246/nphMotionJpeg?Resolution=320x240&amp;Quality=Motion" name="NewPosition"></input>';
        }

        var tmpl = '<div class="lightbox info webcams" style="display: none;" id="lightbox_offer"><div class="header">Webcam</div><div class="content"><h2>{text}</h2>{content}</div><a class="close">{close}</a></div>',
			  text = (lang === 'dk') ? 'ved restaurant ”til Knude Dyb”' : 'Am Restaurant ”til Knude Dyb”',
                content = tmpContent,
             close = (lang === 'dk') ? 'Luk' : 'Schließen',
		     id = $(this).attr('data-house');

        out = template(tmpl, { 'text': text, 'content': content, 'close': close });

        $(out).appendTo('body').lightbox_me({ overlayCSS: { opacity: 1 }, centered: true });

        return false;
    });

    // Search houses by ID
    $('#numberSearch a').click(function () {
        var $this = $(this);
        if ($this.hasClass('active')) {
            $('#numberSearchForm').slideUp(200, function () { $this.toggleClass('active'); });
        } else {
            $this.toggleClass('active');
            $('#numberSearchForm').slideDown(300);
        }
    });
    $('#numberSearchForm').hide();

    //Breadcrumb Fix
    var dkBrdCrmb = $('#breadcrumb li:eq(2) a').attr('href', function (i, href) {
        return href + "?h=" + getParameterByName("h") + "&df=" + getParameterByName("df");
    });


    // Validate Newsletter
    var nlText = {
        'de': {
            'cm-name': "(Geben Sie ihren Namen)",
            'cm-mqltj-mqltj': "(Geben Sie Ihren E-Mail)"
        },
        'dk': {
            'cm-name': "(Indtast et navn)",
            'cm-mqltj-mqltj': "(Indtast gyldig e-mail)"
        }
    };

    $("#newsLetterForm").validate({
        rules: {
            'cm-name': "required",
            'cm-mqltj-mqltj': {
                required: true,
                email: true
            }
        },
        messages: nlText[lang]
    });

    // Offer Date Picker 

    if ($('.offerDatepicker').length != 0) {
        var enabledOfferDays;
        // Enable a list of dates
        function enableTheseDays(date) {
            for (i = 0; i < enabledOfferDays.length; i++) {
                var txtDate = (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear();
                if (($.inArray(txtDate, enabledOfferDays) != -1)) {
                    return [true];
                }
            }
            return [false];
        }

        $.ajax({ type: "POST",
            url: "/services/dhd.asmx/GetGoodOfferDates",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                enabledOfferDays = msg.d;
            }
        });

        //offerpopup
        $('.offerDatepicker').datepicker({
            dateFormat: 'dd-mm-yy',
            beforeShowDay: enableTheseDays,
            firstDay: 1
        });


    }


    $('#showMoreOffers').click(function () {
        $('#lightbox_MoreOffers').lightbox_me({ overlayCSS: { opacity: 1 }, centered: true });
        return false;
    });

    /*DISABLED with new offer system */
    //    if ($('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_cbLastMinuteTilbud:checked').length != 0) {
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_tbAnkomst').attr('readonly', 'readonly');
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_ddlVarighed').attr('disabled', 'disabled');
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_tbAnkomst').datepicker("destroy");

    //        //Labels
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_lblAnkomst').addClass('disabled');
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_lblVarighed').addClass('disabled');

    //        //Fields
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_tbAnkomst').addClass('disabled');
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_ddlVarighed').addClass('disabled');
    //        $('#uniform-ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_ddlVarighed').addClass('disabled');

    //        $('#offerBox').show();
    //    }
    //    else {
    //        $('#ContentPlaceHolderDefault_Indhold_subIndhold_FindSommerhusOversigt_8_tbAnkomst').attr('disabled', '');

    //    }

    // German translation fixes



    if (lang == 'de') {
        $('.facebookNews').text('Neues aus Vejers');
        $('#numberSearch a').text('Ferienhaus anzeigen');
        $('#numberSearchForm label').text('Haus Nr.:');
        $('#numberSearchForm .submit').attr('value', 'Suche');
        $('#numberSearchForm').attr('action', '/de/suche-ferienhaus/ansehen.aspx');
        $('#popupSeasonCalendar').html('<span class="question">?</span>Saisonkalender');
        $('#breadcrumb li:eq(0) span').html('Ferienhaus Suche');
        $('#houseMore .moreLink a').text('Weitere Fotos');

    }

    $('.tiptipGo').tipTip().click(function () { return false; });
});
