﻿var Search = function(){
    var priv = {
    
        tooltipText : null,
		toolTipWidth : null,
		toolTipBodyWidth : null,
		toolTipHeight : null,
		toolTipBodyHeight : null,
    
        toolTip : function($element) {           
            var leftMargin = 10;
            
            $element.mousemove(function(e){
                var toolTipId = '#info_tooltip';	
			    
			    var left = 0;
		        if(priv.toolTipBodyWidth < (e.pageX+leftMargin+priv.toolTipWidth)){
                   left = (e.pageX-leftMargin-priv.toolTipWidth);
                } else {
                   left = (e.pageX+leftMargin);
                }
                var top = 0;
                if(priv.toolTipBodyHeight < (e.pageY+10+priv.toolTipHeight)){
                   top = (e.pageY-10-priv.toolTipHeight);
                } else {
                   top = (e.pageY+10);
                }
                
                $(toolTipId).css({'top':top+'px','left':left+'px'});
            });
            
            $element.hover(
                function () {
                    priv.toolTipBodyHeight = Logic.getBottomPage();
                    priv.toolTipBodyWidth = $('body').width();

                    // normal tooltip
                    var countNr = $(this).attr('rel').split(',')[0];
                    if((countNr+'|').indexOf('- 1|') != -1)
                        priv.tooltipText = countNr + ' accommodatie';
                    else
                        priv.tooltipText = countNr + ' accommodaties';
                    
                    if(priv.tooltipText != ''){
                        if($('#info_tooltip').length == 0){
		                    $('body').append($('<div id="info_tooltip">').css({'position':'absolute','width':'auto'}));
		                    $('#info_tooltip').html(priv.tooltipText);
		                } else {
		                    $('#info_tooltip').html(priv.tooltipText);
		                    $('#info_tooltip').show();
		                }
		            }
		            
		            priv.toolTipWidth = $('#info_tooltip').width();
		            priv.toolTipHeight = $('#info_tooltip').height();
                },
                function () {
                    // normal tooltip
                    $('#info_tooltip').hide();
                }
            );
        },
    
        buildDepartureCalendar : function(){
	        $('div.result-selected .remove').each(function (i) {
                if (this.href.indexOf('daterange=-1') != -1) {
                    this.href = 'javascript:void(0);';
                    $(this).click(function () {
                        Search.changeDateRange('-1');
                    });
                }
            });
	    
            // get the number of days to select before and after the selected date
		    var daterange = Logic.getURLParam('daterange');
		    var addDays = 3;
            if(daterange == '1') {
                addDays = 0;
            } 
            else if(daterange == '3') {
                addDays = 7;
            } else if(daterange == '-1'){
                Search.changeDateRange();
            }
            // get the selected date and get the mindate and maxdate in the range
            var curMinDate = 0;
            var curMaxDate = 0;
            var curSelDate = Logic.getURLParam('seldate');
            if(curSelDate != ''){
                var dtCurSelDate = Date.fromString(curSelDate.substring(6,8)+'/'+curSelDate.substring(4,6)+'/'+curSelDate.substring(0,4));
                curMinDate = parseInt(dtCurSelDate.addDays(addDays*-1).asString2());
	            curMaxDate = parseInt(dtCurSelDate.addDays(addDays*2).asString2());
	            //$('select.daterange option:selected ~ option').remove();
	        } else {
	            $('select.daterange option').show();
	        }
	        // build the departure calendar
		    $('#start-date').datePicker({   inline:true,
		                                    createButton:false,
		                                    showYearNavigation:false,
		                                    year: curYear,
		                                    month: curMonth,
		                                    startDate:firstDate,
				                            endDate:lastDate,
				                            renderCallback:function($td, thisDate, month, year)
				                            {
				                                // set the dates selected inside the range
				                                if(thisDate.asString2() == curSelDate){
				                                    $td.addClass('selected');
				                                    $td.addClass('click');
				                                }
				                                else {
				                                    if(thisDate.asString2() >= curMinDate && thisDate.asString2() <= curMaxDate){
				                                        $td.addClass('selected');
				                                        //$td.addClass('disabled');
				                                    }
				                                }
				                                // disable the dates the aren't departuredays
					                            if (departDates[thisDate.asString2()] == null ||
					                                departDates[thisDate.asString2()] == '') {
						                            $td.addClass('disabled');
					                            } else if(location.href.indexOf('search.aspx') == -1){
					                                // set the tooltip with the number of offers or accommodations
					                                if(departDates[thisDate.asString2()].indexOf(' - 0,') == -1){	
					                                    $td.addClass('tooltip');
					                                    priv.toolTip($td);
					                                }
					                                $td.attr('rel', departDates[thisDate.asString2()]);
					                            }
				                            }});
			
			// bind the action when a date is clicked
			$('#start-date').bind(
			    'dateSelected',
			    function(e, selectedDate, $td)
			    {
			        // get the information from the rel (<countnr>,<querystring>,<nvalue>)
		            //var rel = $td.attr('rel');
		            // do not fire click when clicked on a date that is already selected
		            //if(rel.substring(0,2) != '0,'){
		            //if(curSelDate == null || curSelDate == ''){
		                if(daterange == '-1') {
		                    $('select.daterange').val('2');
		                }
		                
		                // get the selected daterange
		                var minDate = parseInt(selectedDate.addDays(addDays*-1).asString2());
		                var maxDate = parseInt(selectedDate.addDays(addDays*2).asString2());
		                selectedDate = selectedDate.addDays(addDays*-1);
		                
		                var selectQuery = '';
		                var selNValues = '';
		                // loop through the date range and build the string with the nvalues to select
		                // - and build the string with all the querystrings
		                for(var i=minDate;i<=maxDate;i++){
		                    if(departDates[i] != null && departDates[i] != ''){
		                        var queryString = departDates[i].split(',')[1];
		                        var nValue = departDates[i].split(',')[2];
		                        selNValues += selNValues == '' ? nValue : '+'+nValue;
		                        
		                        var startIndex = queryString.indexOf('N=');
		                        if(startIndex != -1){
		                            var endIndex = queryString.indexOf('&', startIndex);
		                            if(endIndex == -1){
		                                endIndex = queryString.length+1;
		                            }
		                            selectQuery += '||'+queryString.substring(startIndex+2,endIndex).replace(/\+/g,'||');
		                        }
		                    }
		                }
		                selectQuery += '|';
		                
		                // remove the departuredays nvalues, so only the other nvalues are left over
		                for(var key in departDates){
		                    var nValue = departDates[key].split(',')[2];
		                    if(selectQuery.indexOf('|'+nValue+'|') != -1){
		                        selectQuery = selectQuery.replace(new RegExp('/|'+nValue+'|/','g'),'');
		                    }
		                }
		                
		                // combine the to selected departuredays nvalues with the other selected nvalues
		                var splitOtherNvalues = selectQuery.split('|');
		                for(var i=0;i<splitOtherNvalues.length;i++){
		                    if(splitOtherNvalues[i] != '' && ('+'+selNValues+'+').indexOf('+'+splitOtherNvalues[i]+'+') == -1){
		                        selNValues += '+'+splitOtherNvalues[i];
		                    }
		                }
		                
		                // submit the selected date range
		                var strUrl = location.href;
		                if(strUrl.indexOf('?') == -1){
		                    location.href = location.href + '?N='+selNValues+'&seldate='+selectedDate.asString2();
		                } else {
		                    var params = Logic.removeURLParam(location.href.split('?')[1],'seldate');
		                    params = Logic.removeURLParam(params,'No');
		                    params = Logic.removeURLParam(params,'N');
		                    if(params != '' && params.substring(0,1) != '&') params = '&'+params; 
		                    location.href = location.href.split('?')[0] + '?N='+selNValues+'&seldate='+selectedDate.asString2()+params;
		                }
		            //} else {
		            //    // deselect range, when clicked on a currently selected date
		            //    Search.changeDateRange(-1);
		            //}
			    }
		    );
        
        },
        
        bindEvents : function(){
            // bind lister hovers
            $("#list>li").hover(
                function () {
                    $(this).addClass("hover");
                }, 
                function () {
                    $(this).removeClass("hover");
                }
            ).bind("click", 
                function(evt){
                    var url = $("a:eq(0)", this).attr("href");
                    if(url){
                        document.location.href = url;
                    }
                }
            );
        }
        
    };
        
    return {
    
        changeDateRange : function(parDaterange){
	        var daterangeVal = parDaterange;
	        if(daterangeVal == null)
	            daterangeVal = $('select.daterange').val();
	        var nValues = Logic.getURLParam('N');
	        if(daterangeVal == '-1'){
	            if(location.href.indexOf('?') != -1){
	                // undo departure filter
	                var queryString = location.href.split('?')[1];
	                var arrnValues = nValues.split('+');
	                var newNvalues = '';
	                if(typeof(allDepartureDays) != "undefined"){
	                    for(var i=0;i<arrnValues.length;i++){
                            if(allDepartureDays.indexOf('|'+arrnValues[i]+'|') != -1){

                                arrnValues[i] = '';
                            }
                        }
	                } else {
	                    for(var key in departDates){
                            var nValue = departDates[key].split(',')[2];
                            for(var i=0;i<arrnValues.length;i++){
                                if(nValue == arrnValues[i]){
                                    arrnValues[i] = '';
                                }
                            }
                        }
                    }
                    for(var i=0;i<arrnValues.length;i++){
                        if(arrnValues[i] != ''){
                            newNvalues += newNvalues == '' ? arrnValues[i] : '+'+arrnValues[i];
                        }
                    }
                    if(newNvalues == ''){
                        newNvalues = '0';
                    }
                    queryString = Logic.removeURLParam(queryString,'seldate');
                    //queryString = Logic.removeURLParam(queryString,'daterange');
                    queryString = Logic.removeURLParam(queryString,'No');
                    queryString = Logic.removeURLParam(queryString,'N');
                    if(queryString != '' && queryString.substring(0,1) != '&') queryString = '&'+queryString;
                    location.href = location.href.split('?')[0] + '?N='+newNvalues+queryString;
                }
	        } else {
	            if(location.href.indexOf('?') == -1){
	                location.href = location.href + '?daterange='+daterangeVal;
	            } else {
	                var curSelDate = Logic.getURLParam('seldate');
	                var nValues = Logic.getURLParam('N');
	                if(curSelDate != '' && nValues != ''){
	                    var addDays = 3;
                        if(daterangeVal == '1') {
                            addDays = 0;
                        } 
                        else if(daterangeVal == '3') {
                            addDays = 7;
                        }
                        // get the selected date and get the mindate and maxdate in the range
                        var minDate = 0;
                        var maxDate = 0;
                        if(curSelDate != ''){
                            var dtCurSelDate = Date.fromString(curSelDate.substring(6,8)+'/'+curSelDate.substring(4,6)+'/'+curSelDate.substring(0,4));
                            minDate = parseInt(dtCurSelDate.addDays(addDays*-1).asString2());
	                        maxDate = parseInt(dtCurSelDate.addDays(addDays*2).asString2());
	                    }
	                    var newNvalues = '';
	                    var selectQuery = '';
		                var selNValues = '';
		                // loop through the date range and build the string with the nvalues to select
		                // - and build the string with all the querystrings
		                for(var i=minDate;i<=maxDate;i++){
		                    if(departDates[i] != null && departDates[i] != ''){
		                        var queryString = departDates[i].split(',')[1];
		                        var nValue = departDates[i].split(',')[2];
		                        selNValues += selNValues == '' ? nValue : '+'+nValue;
		                        
		                        var startIndex = queryString.indexOf('N=');
		                        if(startIndex != -1){
		                            var endIndex = queryString.indexOf('&', startIndex);
		                            if(endIndex == -1){
		                                endIndex = queryString.length+1;
		                            }
		                            selectQuery += '||'+queryString.substring(startIndex+2,endIndex).replace(/\+/g,'||');
		                        }
		                    }
		                }
		                selectQuery += '|';
		                
		                // remove the departuredays nvalues, so only the other nvalues are left over
		                for(var key in departDates){
		                    var nValue = departDates[key].split(',')[2];
		                    if(selectQuery.indexOf('|'+nValue+'|') != -1){
		                        selectQuery = selectQuery.replace(new RegExp('/|'+nValue+'|/','g'),'');
		                    }
		                }
		                
		                // combine the to selected departuredays nvalues with the other selected nvalues
		                var splitOtherNvalues = selectQuery.split('|');
		                for(var i=0;i<splitOtherNvalues.length;i++){
		                    if(splitOtherNvalues[i] != '' && ('+'+selNValues+'+').indexOf('+'+splitOtherNvalues[i]+'+') == -1){
		                        selNValues += '+'+splitOtherNvalues[i];
		                    }
		                }
    
                        newNvalues = selNValues;
	                    if(newNvalues == ''){
	                        newNvalues = '0';
	                    }
	                    var queryString = location.href.split('?')[1];
	                    queryString = Logic.removeURLParam(queryString,'daterange');
	                    queryString = Logic.removeURLParam(queryString,'No');
	                    queryString = Logic.removeURLParam(queryString,'N');
	                    location.href = location.href.split('?')[0] + '?N='+newNvalues+'&daterange='+daterangeVal+queryString;
	                } else {
	                    location.href = location.href.split('?')[0] + '?'+Logic.removeURLParam(location.href.split('?')[1],'daterange')+'&daterange='+daterangeVal;
	                }
	            } 
	        }
	    },
    
    	        
        ddDestinations_change : function()
        {
            location.href = $('#ddDestinations option:selected').val();
        },
    
        OnReady	: function(){
			priv.bindEvents();
			
			if(typeof(curYear) != "undefined") {
		        priv.buildDepartureCalendar();
		    }
		}
		
    }
}(jQuery);
