﻿var travelers = function($){
    var priv = {
            cookieName : 'occupancy',
            cookieExpires : 30,
            
            filterSearch : 1,
			nrAdults : -1,
			nrChildren : -1,
			nrBabies : -1,
			arrAdults : null,
			arrChildren : null,
			arrBabies : null,
			initialized : false,
					
			birthDaysCheck : function () {
			    if(priv.nrChildren > 0 || priv.nrBabies > 0){
			        var curDate = new Date();
			        var babyMaxYear = curDate.getFullYear();
			        var babyMinYear = curDate.getFullYear()-2;
			        var childMaxYear = curDate.getFullYear()-2;
			        var childMinYear = curDate.getFullYear()-17;
			        var selected = ' selected="selected"';
			        
			        var dayOptions = '';
			        for(var i=1;i<=31;i++){
			            dayOptions += '<option';
			            if(i==20){
			                dayOptions += selected;
			            }
			            dayOptions += '>'+i+'</option>';
			        }
			        var monthOptions = '';
			        for(var i=0;i<12;i++){
			            monthOptions += '<option';
			            if(i==2){
			                monthOptions += selected;
			            }
			            monthOptions += '>'+resources.date_months_long[i]+'</option>';
			        }
			        var childYearOptions = '';
			        for(var i=childMinYear;i<=childMaxYear;i++){
			            childYearOptions += '<option';
			            if( i == ( parseInt((childMaxYear-childMinYear)/2) + childMinYear ) ){
			                childYearOptions += selected;
			            }
			            childYearOptions += '>'+i+'</option>';
			        }
			        var babyYearOptions = '';
			        for(var i=babyMinYear;i<=babyMaxYear;i++){
			            babyYearOptions += '<option';
			            if( i == ( ( (babyMaxYear-babyMinYear)/2) + babyMinYear ) ){
			                babyYearOptions += selected;
			            }
			            babyYearOptions += '>'+i+'</option>';
			        }
			    
			        // add children date of birth selections
			        if(priv.nrChildren > 0){
			            if($('#children').html() == ''){
			                $('#children').html('<span>Geboortedata kinderen:</span><br/>');
			            }
			        } else {
			            $('#children').html('');
			        }
			        priv.buildBirthDayDropDowns('#children', 'childrow', priv.nrChildren, dayOptions, monthOptions, childYearOptions);
			        
			        //add babies day of birth selections
			        if(priv.nrBabies > 0){
			            if($('#babies').html() == ''){
			                $('#babies').html('<span>Geboortedata baby\'s:</span><br/>');
			            }
			        } else {
			            $('#babies').html('');
			        }
			        priv.buildBirthDayDropDowns('#babies', 'babyrow', priv.nrBabies, dayOptions, monthOptions, babyYearOptions);
			    
	                $('#birthdays').show();
	                logic.resizePopup();
	                logic.callBackResizePopup();
	            } else {
	                $('#birthdays #children').html('');
	                $('#birthdays #babies').html('');
	                $('#birthdays').hide();
	                logic.resizePopup();
	                logic.callBackResizePopup();
	            }
			},
			
            isDate : function(year, month, day) {
                // set number of days in a month
	            var daysInMonth = new Array();
	            for (var i = 1; i <= 12; i++) {
		            daysInMonth[i] = 31;
		            if (i==4 || i==6 || i==9 || i==11) {daysInMonth[i] = 30;}
		            if (i==2) {daysInMonth[i] = 29;}
                }
                // February has 29 days in any year evenly divisible by four,
                // EXCEPT for centurial years which are not also divisible by 400.
                var daysInFebruary = (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
                // check if date is valid
	            if (( (month+1) == 2 && day > daysInFebruary) || day > daysInMonth[month+1]){
		            return false;
	            }
                return true;
            },
			
			checkBirthDaysCorrect : function(){
			    var hasInvalidDate = false;
			    $('#birthdays #children .childrow').each(function (i) {
			        var invalidItemDate = false;
                    var day = $('#day', this).val();
                    var month = $('#month', this).get(0).selectedIndex;
                    var year = $('#year', this).val();
                    
                    if(!priv.isDate(year,month,day)){
                        $('#birthdays #children .rowerror:eq('+i+')').text('Vul hierboven een correcte datum in.');
                        invalidItemDate = true;
                    }
                    
                    var inputDate = new Date(year,month,day);
	                
	                var today = new Date();
	                var minDate = new Date(today.getFullYear()-17,today.getMonth(),today.getDate());
	                var maxDate = new Date(today.getFullYear()-2,today.getMonth(),today.getDate());
	                if(inputDate < minDate || inputDate > maxDate){
	                    $('#birthdays #children .rowerror:eq('+i+')').text('De bovenstaande datum moet liggen tussen '+minDate.getDate()+' '+resources.date_months_short[minDate.getMonth()]+' '+minDate.getFullYear()+' en '+maxDate.getDate()+' '+resources.date_months_short[maxDate.getMonth()]+' '+maxDate.getFullYear()+'.');
                        invalidItemDate = true;
	                }
	                
	                if(!invalidItemDate){
	                    $('#birthdays #children .rowerror:eq('+i+')').text('');
	                } else {
	                    hasInvalidDate = invalidItemDate;
	                }
                });
                
                $('#birthdays #babies .babyrow').each(function (i) {
                    var invalidItemDate = false;
                    var day = $('#day', this).val();
                    var month = $('#month', this).get(0).selectedIndex;
                    var year = $('#year', this).val();
                    
                    if(!priv.isDate(year,month,day)){
                        $('#birthdays #babies .rowerror:eq('+i+')').text('Vul hierboven een correcte datum in.');
                        invalidItemDate = true;
                    }
                    
                    var inputDate = new Date(year,month,day);
	                
	                var today = new Date();
	                var minDate = new Date(today.getFullYear()-2,today.getMonth(),today.getDate());
	                var maxDate = today;
	                if(inputDate < minDate || inputDate > maxDate){
	                    $('#birthdays #babies .rowerror:eq('+i+')').text('De bovenstaande datum moet liggen tussen '+minDate.getDate()+' '+resources.date_months_short[minDate.getMonth()]+' '+minDate.getFullYear()+' en '+maxDate.getDate()+' '+resources.date_months_short[maxDate.getMonth()]+' '+maxDate.getFullYear()+'.');
                        invalidItemDate = true;
	                }
	                
	                if(!invalidItemDate){
	                    $('#birthdays #babies .rowerror:eq('+i+')').text('');
	                } else {
	                    hasInvalidDate = invalidItemDate;
	                }
                });

			    return !hasInvalidDate;
			},
			
			buildBirthDayDropDowns : function (holderId, rowClass, nrOfType, dayOptions, monthOptions, yearOptions) {
			    //add day of birth selections
		        var alreadyAdded = $('#birthdays '+holderId+' .'+rowClass).length;
		        // less children selected than before, remove the children that are above the limit
		        if(alreadyAdded > nrOfType){
		            for(var i=(alreadyAdded-1);i>=nrOfType;i--){
		                $('#birthdays '+holderId+' .'+rowClass+':eq('+i+')').remove();
		                if(nrOfType > 1 && i==nrOfType){
		                    $('#birthdays '+holderId+' .'+rowClass+':eq('+(i-1)+')').removeClass('middle');
		                    $('#birthdays '+holderId+' .'+rowClass+':eq('+(i-1)+')').addClass('last');
		                }
		            }
		        } 
		        // there are more children selected than before, add the extra children
		        else {
		            var className = 'first';
		            for(var i=0;i<nrOfType;i++){
		                if(i==(nrOfType-1)){
		                    className = 'last'; 
		                } else if(i>0){
		                    className = 'middle';
		                }
			            
			            if(i<alreadyAdded){
			                $('#birthdays '+holderId+' .'+rowClass+':eq('+i+')').removeClass('last');
		                    $('#birthdays '+holderId+' .'+rowClass+':eq('+i+')').addClass(className);
			            } else {
		                    var row = '<div class="'+rowClass+' '+className+'">'+
                                            (i+1)+') '+
                                            '<select id="day">'+
                                                dayOptions+
                                            '</select> '+
                                            '<select id="month">'+
                                                monthOptions+
                                            '</select> '+
                                            '<select id="year">'+
                                                yearOptions+
                                            '</select>'+
                                        '</div>';
                                        
                            $('#birthdays '+holderId).append(row+'<div class="rowerror"></div>');
                        }
		            }
		        }
			},
			
			bindPopupEvents : function () {
			    if(!priv.initialized){
			        $('#birthdays #children').html('');
	                $('#birthdays #babies').html('');
	                
			        priv.loadCookie();
			        
			        $('#nr-adults').val(priv.nrAdults);
			        $('#nr-children').val(priv.nrChildren);
			        $('#nr-babies').val(priv.nrBabies);
			        if(priv.filterSearch == 0){
			            $('#chkFilter').removeAttr('checked');
			        }
			        
			        priv.birthDaysCheck();			            
                    
                    $('#birthdays #children .childrow').each(function (i) {
                        $('#day', this).val(priv.arrChildren[i].geboortedatum.getDate());
                        $('#month', this).get(0).selectedIndex = priv.arrChildren[i].geboortedatum.getMonth();
                        $('#year', this).val(priv.arrChildren[i].geboortedatum.getFullYear());
                    });
                    $('#birthdays #babies .babyrow').each(function (i) {
                        $('#day', this).val(priv.arrBabies[i].geboortedatum.getDate());
                        $('#month', this).get(0).selectedIndex = priv.arrBabies[i].geboortedatum.getMonth();
                        $('#year', this).val(priv.arrBabies[i].geboortedatum.getFullYear());
                    });
			    
			        $('#nr-adults').bind("change", function(){
			            var newValue = parseInt($('#nr-adults').val());
			            if(newValue == 0){
			                priv.arrAdults = new Array();
			            } else {
			                if(newValue < priv.nrAdults) {
			                    priv.arrAdults = priv.arrAdults.slice(0,newValue);
			                } else if(newValue > priv.nrAdults){
			                    for(var i=priv.nrAdults;i<newValue;i++){
			                        var addPart = new Participant();
                                    addPart.type = 'Adult';
			                        priv.arrAdults[i] = addPart;
			                    }
			                }
			            }
			            
			            priv.nrAdults = newValue;
                    });
                    
                    $('#nr-children').bind("change", function(){
                        var newValue = parseInt($('#nr-children').val());
                        if(newValue == 0){
			                priv.arrChildren = new Array();
			            } else {
			                if(newValue < priv.nrChildren) {
			                    priv.arrChildren = priv.arrChildren.slice(0,newValue);
			                } else if(newValue > priv.nrChildren){
			                    for(var i=priv.nrChildren;i<newValue;i++){
			                        var addPart = new Participant();
                                    addPart.type = 'Child';
			                        priv.arrChildren[i] = addPart;
			                    }
			                }
			            }
			            
			            priv.nrChildren = newValue;
			            priv.birthDaysCheck();			            
                    });
                    
                    $('#nr-babies').bind("change", function(){
                        var newValue = parseInt($('#nr-babies').val());
                        if(newValue == 0){
			                priv.arrBabies = new Array();
			            } else {
			                if(newValue < priv.nrBabies) {
			                    priv.arrBabies = priv.arrBabies.slice(0,newValue);
			                } else if(newValue > priv.nrBabies){
			                    for(var i=priv.nrBabies;i<newValue;i++){
			                        var addPart = new Participant();
                                    addPart.type = 'Baby';
			                        priv.arrBabies[i] = addPart;
			                    }
			                }
			            }
                    
                        priv.nrBabies = newValue;			            
			            priv.birthDaysCheck();
                    });
                    
                    $('#chkFilter').bind("click", function(){
                        priv.filterSearch = this.checked ? 1 : 0;
                    });
                    
                    priv.initialized = true;
                }
			},
			
			loadCookie : function () {
			    var cookieStr = $.cookie(logic.CookiePrefix + priv.cookieName);
			    if(cookieStr == null || cookieStr == '' || cookieStr.indexOf('<OCCUPANCY') == -1){
			        priv.filterSearch = 1;
			        priv.nrAdults = 0;
	                priv.nrChildren = 0;
	                priv.nrBabies = 0;
	                priv.arrAdults = new Array();
	                priv.arrChildren = new Array();
	                priv.arrBabies = new Array();
	                
	                priv.deleteCookie();
	                return;
			    }
			
			    try {
			        var xmlDoc = null;
			        if (window.ActiveXObject)
                    {
                        // code for IE
                        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                        xmlDoc.async="false";
                        xmlDoc.loadXML(cookieStr);
                    }
                    else {
                        // code for Mozilla, Firefox, Opera, etc.
                        var parser=new DOMParser();
                        xmlDoc = parser.parseFromString(cookieStr,"text/xml");
                    }
			        var root = xmlDoc.documentElement;
			        
			        // set values from cookie
			        priv.nrAdults = parseInt(root.getAttribute("ADULTS"));
	                priv.nrChildren = parseInt(root.getAttribute("CHILDS"));
	                priv.nrBabies = parseInt(root.getAttribute("BABYS"));
	                priv.filterSearch = parseInt(root.getAttribute("USEFORSEARCH"));

	                // set date arrays
	                priv.arrAdults = new Array();
	                priv.arrChildren = new Array();
	                priv.arrBabies = new Array();
	                var xmlParticipants = xmlDoc.documentElement.getElementsByTagName("PART");
	                var adultCount = 0;
	                var childCount = 0;
	                var babyCount = 0;
	                for (var i = 0; i < xmlParticipants.length; i++) {
	                    var addParticipant = new Participant();
	                    addParticipant.volgnr = xmlParticipants[i].getAttribute("VOLGNR");
                        addParticipant.type = xmlParticipants[i].getAttribute("TYPE");
                        addParticipant.aanhef = xmlParticipants[i].getAttribute("AANHEF");
                        addParticipant.voornaam = xmlParticipants[i].getAttribute("VOORNAAM");
                        addParticipant.tussenvoegsel = xmlParticipants[i].getAttribute("TUSSENVOEGSEL");
                        addParticipant.achternaam = xmlParticipants[i].getAttribute("ACHTERNAAM");
                        var birthDate = xmlParticipants[i].getAttribute("GEBOORTEDATUM");
                        
                        //catch some data errors:
                        //remove dates that contain '0:00:00'
                        if(birthDate.indexOf(':') != -1){
                            birthDate = null;
                        }                       
                        if(birthDate != null && birthDate != ''){
                            //replace the '/' with '-', since we are now out of sync with booking steps logic
                            birthDate = birthDate.replace(/\//g, '-');
                            var spltbirthDate = birthDate.split('-');
	                        var date = new Date();
	                        date.setFullYear(spltbirthDate[2],parseInt(spltbirthDate[1])-1,spltbirthDate[0]);
                            addParticipant.geboortedatum = date;
                            logic.writeDebug(addParticipant.type + ":" + date.toString());
                        }
                        
                        if(addParticipant.type == 'A' || addParticipant.type == 'Adult'){
                            priv.arrAdults[adultCount] = addParticipant;
                            adultCount++;
                        } else if(addParticipant.type == 'C' || addParticipant.type == 'Child'){
                            priv.arrChildren[childCount] = addParticipant;
                            childCount++;
                        } else if(addParticipant.type == 'B' || addParticipant.type == 'Baby'){
                            priv.arrBabies[babyCount] = addParticipant;
                            babyCount++;
                        } 
	                }

                }
                catch(err) {
                    logic.writeDebug(err);
                    // broken cookie, delete and set default values
                    priv.deleteCookie();
                    priv.filterSearch = 1;
			        priv.nrAdults = 0;
	                priv.nrChildren = 0;
	                priv.nrBabies = 0;
	                priv.arrAdults = new Array();
	                priv.arrChildren = new Array();
	                priv.arrBabies = new Array();
                }
			},
			
			saveCookie : function () {
			    // than add the birthdays of the children and babies
			    $('#birthdays #children .childrow').each(function (i) {
			        var newDate = new Date();
			        newDate.setFullYear($('#year', this).val(),$('#month', this).get(0).selectedIndex,$('#day', this).val());
                    logic.writeDebug('1) ' + i + ' - ' + newDate);
                    priv.arrChildren[i].geboortedatum = newDate;
                    logic.writeDebug('2) ' + i + ' - ' + priv.arrChildren[i].geboortedatum);
                });
                for(var i=0;i<priv.arrChildren.length;i++){
                    logic.writeDebug('3) ' + i + ' - ' + priv.arrChildren[i].geboortedatum);
                }
                $('#birthdays #babies .babyrow').each(function (i) {
			        var newDate = new Date();
			        newDate.setFullYear($('#year', this).val(),$('#month', this).get(0).selectedIndex,$('#day', this).val());
                    priv.arrBabies[i].geboortedatum = newDate;
                });
			    
			    // build the cookie string
			    var cookieStr = '<OCCUPANCY PARTICIPANTS="'+travelers.getOccupancy()+'" ADULTS="'+priv.nrAdults+'" CHILDS="'+priv.nrChildren+'" BABYS="'+priv.nrBabies+'" USEFORSEARCH="'+priv.filterSearch+'">';

                for(var i=0;i<priv.arrAdults.length;i++){
                    var curPart = priv.arrAdults[i];
                    var birthDate = '';
                    if(curPart.geboortedatum != null){
                        var curDate = curPart.geboortedatum;
                        birthDate = curDate.getDate()+'-'+(curDate.getMonth()+1)+'-'+curDate.getFullYear();
                    }
                    else {
                        //little hack for the bookingsteps
                        birthDate = '0:00:00';
                    }
                    cookieStr += '<PART VOLGNR="'+curPart.volgnr+'" TYPE="'+curPart.type+'" AANHEF="'+curPart.aanhef+'" VOORNAAM="'+curPart.voornaam+'" TUSSENVOEGSEL="'+curPart.tussenvoegsel+'" ACHTERNAAM="'+curPart.achternaam+'" GEBOORTEDATUM="'+birthDate+'" />';
                }
                for(var i=0;i<priv.arrChildren.length;i++){
                    var curPart = priv.arrChildren[i];
                    var birthDate = '';
                    if(curPart.geboortedatum != null){
                        var curDate = curPart.geboortedatum;
                        birthDate = curDate.getDate()+'-'+(curDate.getMonth()+1)+'-'+curDate.getFullYear();
                    }
                    cookieStr += '<PART VOLGNR="'+curPart.volgnr+'" TYPE="'+curPart.type+'" AANHEF="'+curPart.aanhef+'" VOORNAAM="'+curPart.voornaam+'" TUSSENVOEGSEL="'+curPart.tussenvoegsel+'" ACHTERNAAM="'+curPart.achternaam+'" GEBOORTEDATUM="'+birthDate+'" />';
                }
                for(var i=0;i<priv.arrBabies.length;i++){
                    var curPart = priv.arrBabies[i];
                    var birthDate = '';
                    if(curPart.geboortedatum != null){
                        var curDate = curPart.geboortedatum;
                        birthDate = curDate.getDate()+'-'+(curDate.getMonth()+1)+'-'+curDate.getFullYear();
                    }
                    cookieStr += '<PART VOLGNR="'+curPart.volgnr+'" TYPE="'+curPart.type+'" AANHEF="'+curPart.aanhef+'" VOORNAAM="'+curPart.voornaam+'" TUSSENVOEGSEL="'+curPart.tussenvoegsel+'" ACHTERNAAM="'+curPart.achternaam+'" GEBOORTEDATUM="'+birthDate+'" />';
                }
                
                cookieStr += '</OCCUPANCY>';
                // save the cookie
			    $.cookie(logic.CookiePrefix + priv.cookieName, cookieStr, { expires: priv.cookieExpires, path: '/' });
			},
			
			deleteCookie : function () {
			    $.cookie(logic.CookiePrefix + priv.cookieName, '', { expires: -1, path: '/' });
			}
    };
    
    return {
        
        showTravelersPopup : function () {
            priv.initialized = false;
	        logic.showPopup('pTravelers', true, 285, 0);
	        logic.resizePopup();
	        
	        priv.bindPopupEvents();
	    },
	    
	    getNrAdults : function () {
	        return parseInt(priv.nrAdults);
	    },
	    
	    getNrChildren : function () {
	        return parseInt(priv.nrChildren);
	    },
	    
	    getNrBabies : function () {
	        return parseInt(priv.nrBabies);
	    },
	    
	    getOccupancy : function () {
	        return parseInt(priv.nrAdults) + parseInt(priv.nrChildren);
	    },
	    
	    getStrOccupancy : function () {
	        var strOccupancy = 'Reisgezelschap (<a href="javascript:travelers.showTravelersPopup()" class="drilllink">Selecteer</a>)';
	        
	        if(priv.nrAdults > 0 || priv.nrChildren > 0 || priv.nrBabies > 0){
	            strOccupancy = 'Reisgezelschap (<a href="javascript:travelers.showTravelersPopup()" class="drilllink">Wijzig</a>)<br>';
	            
	            strOccupancy += '<ul class="usp-texts">';
	            // nr adults
	            if(priv.nrAdults == 1){
	                strOccupancy += '<li>1 volwassene</li>';
	            } else if(priv.nrAdults > 1){
	                strOccupancy += '<li>'+priv.nrAdults+' volwassenen</li>';
	            }
	            // nr children
	            if(priv.nrChildren == 1){
	                strOccupancy += '<li>1 kind</li>';
	            } else if(priv.nrChildren > 1){
	                strOccupancy += '<li>'+priv.nrChildren+' kinderen</li>';
	            }
	            // nr babies
	            if(priv.nrBabies == 1){
	                strOccupancy += '<li>1 baby</li>';
	            } else if(priv.nrBabies > 1){
	                strOccupancy += '<li>'+priv.nrBabies+' baby\'s</li>';
	            }
	            strOccupancy += '</ul>';
	        }
	        
	        return strOccupancy;
	    },
	    
	    saveTravelers : function () {
	        // check if the birthdays are correct
	        if(!priv.checkBirthDaysCorrect()){
	            // stop if the birthdays are incorrect
	            return false;
	        } else {
	            // delete cookie if there are no occupants. else save the cookie
	            if(travelers.getOccupancy() == 0){
	                priv.deleteCookie();
	            } else {
	                var nrOfPeople = travelers.getNrAdults() + travelers.getNrChildren() + travelers.getNrBabies();
	                
	                pageTracker._trackEvent('reisgezelschap','submit', nrOfPeople, nrOfPeople);
                    rollupTracker._trackEvent('reisgezelschap','submit', nrOfPeople, nrOfPeople);
                    
	                priv.saveCookie();
	            }
	            // show the new travelers information in the div
	            $('#travelersDiv').html(travelers.getStrOccupancy());
	            logic.hidePopup();
    	        
	            // if on the search page, refresh page to apply new filter
	            if(location.href.indexOf('search.aspx') != -1 || location.href.indexOf('zoeken') != -1 ||
	               location.href.indexOf('offers.aspx') != -1 || location.href.indexOf('aanbiedingen') != -1 ||
	               location.href.indexOf('miniski.aspx') != -1 || location.href.indexOf('petitski') != -1 ||
	               location.href.indexOf('view=prices') != -1){
	                if(location.href.indexOf('#') != -1){
	                    location.href = location.href.substring(0,location.href.indexOf('#'));
	                } else {
	                    location.href = location.href;
	                }
	            }
	        }
	    },
	    
	    setCookieFromDropDown : function(nr)
	    {
	        if (nr == -1)
	        priv.deleteCookie();
	    
            if(nr == 0){
                priv.arrAdults = new Array();
            } else {
                if(nr < priv.nrAdults) {
                    priv.arrAdults = priv.arrAdults.slice(0,nr);
                } else if(nr > priv.nrAdults){
                    for(var i=priv.nrAdults;i<nr;i++){
                        var addPart = new Participant();
                        addPart.type = 'Adult';
                        priv.arrAdults[i] = addPart;
                    }
                }
            }
            
            priv.nrAdults = nr;
            priv.saveCookie();
	    },
	    
	    deleteTravelersCookie : function()
	    {
	        priv.deleteCookie();
	        location.href = location.href;
	    },
	    	    
	    OnReady	: function(){
	        // load the travelers data from cookie
	        priv.loadCookie();
	        
	        // show the travelers information in the div
	        $('#travelersDiv').html(travelers.getStrOccupancy());
	    }
    };
}(jQuery);


var Participant = function($){
    var priv = {
        
    };
    
    return {
        
        volgnr : '',
        type : '',
        aanhef : '',
        voornaam : '',
        tussenvoegsel : '',
        achternaam : '',
        geboortedatum : null
        
    };
};

