﻿/**
 * static object that handles page logic
 * @class 
 * @constructor
 * @param {jQuery} $ Reference to the jQuery object
 */
var HomeMain = function($) {

    /**
     * @namespace Private methods and variables
     */
    var priv = {

		initializeBannerpool: function() {
            try {
				var ulBanner = new BannerPool({ "container": $("ul.banner").get(0), "debuglogger": function(msg) { Log.Debug(msg); } });
                //make the elements clickable
				$("ul.banner li").bind("click",
                    function(evt) {
                        var newloc = $(this).find("a").attr("href");

                        //deterimine if we need to open a new window
                    	if (newloc && $(this).find("a").attr("target") != "") {
                           return;
                        }
                    	else if (newloc) {
                            document.location.href = newloc;
                        }
                    }
                );
            }
			catch (e) {
                Log.Debug("HomeMain : error initializing the bannerpool: " + e.toString());
            }
        },

		bindPromoEvents: function() {
            $('#homepagepromo ul.promotion-blocks').children("li").hover(
                function() { $(this).addClass("hover"); },
                function() { $(this).removeClass("hover"); }
            ).bind("click",
                function() {
                    //redirect to the correct page
                    var url = $(this).find(".promo-acco-name a").attr("href");

                    document.location.href = url;
                    //prevent event bubbling
                    return false;
                }
            );
        },

		bindSearchBoxEvents: function() {
            // Search button
            $('#homesearch').bind("focus",
                function() {
                    this.value = '';
                }
            ).bind("keydown",
                function(evt) {
                	if (evt.keyCode == 13) {
                        priv.inputSubmit();
                    }
                }
            );

            $('#homesearchbutton').bind("click",
                function() {
                   priv.inputSubmit();
                }
            );

                // autocomplete functionality
			$('#homesearch').autocomplete(Resource.GetText('path_prefix') + "/js/ajax/get_searchsuggestions.ashx", {
                	selectFirst: false,
                	delay: 10,
                	width: 140
                }).result(function(event, item) {
                	priv.inputSubmit();
            });
        },

		inputSubmit: function() {
			if ($('#homesearch').val() != null && $('#homesearch').val() != "") {
				$('#homesearch').val($('#homesearch').val().replace('bijv: ', ''));
				location.href = Resource.GetText('searchpage') + '?searchtext=' + encodeURIComponent($('#homesearch').val());
            }
        },

		top10Tooltip: function() {
            //enable tooltips top 10 destinations            
			$('#popularLocations a.plus0').each(function() {
                $(this).jHelperTip({
					trigger: "hover",
					source: "container",
                    dC: "#tip" + $(this).attr('rel'),
                    autoClose: true,
                    topOff: -20,
					leftOff: 30
                });
            });
        },

        bindPromoBlockEvents: function() {
			$("div.promotion-blocks .box-white .inner .content").bind("click",
                function() {
                	document.location.href = $(this).find(".promo-acco-name a").attr("href");
                }
            ).hover(
                function(evt) {
                    $(this).addClass("hover");
                },
                function(evt) {
                    $(this).removeClass("hover");
                }
            );
        },

        bindCountryLocations: function() {
            var $countryPopup = $("div#country-popup");
            $("li.show-country-popup").hover(
		        function() {
		            $(this).addClass("country-selected");
		            $(this).append($countryPopup);
		            $countryPopup.show();
		            if ($(this).parent().parent().hasClass("left")) {
		                $("div#country-popup").css("left", "325px");
		            }
		            if ($(this).parent().parent().hasClass("right")) {
		                $("div#country-popup").css("left", "450px");
		            }
		            return false;
		        },
		        function() {
		            $(this).removeClass("country-selected");
		            $countryPopup.hide();
		            return false;
		        }
		    );
            $("a.remove").click(
	            function() {
	                $countryPopup.hide();
	                return false;
	            }
	        );
		},

		searchbarSelectElement: 'form.vacancy-form select',
		bindSearchbarEvents: function() {
			//priv.buildCalendar();
			$(priv.searchbarSelectElement).bind('change', function() {
				priv.searchbarChange();
			});
		},

		searchbarLock: false,
		setSearchbarLock: function() {
			priv.searchbarLock = true;
			//do some loading animation here
			$(priv.searchbarSelectElement).attr("disabled", "disabled");
			var overlay = document.createElement("DIV");
			var loader = document.createElement("DIV");
			var fullHeight = $('#searchbar').height();
			var fullWidth = $('#searchbar').width()
			$(overlay).css({ "z-index": 4, "opacity": 0.75, "position": "absolute", "top": 0, "left": 0, "background": $('#searchbar').css("background-color") }).height(fullHeight).width(fullWidth);
			$(loader).css({ "position": "absolute", "top": 0, "left": 0, "z-index": 5, "background": "transparent url(images/ajax-loader-searchbar.gif) no-repeat center" }).height(fullHeight).width(fullWidth);
			$("#searchbar fieldset").css("position", "relative").append(overlay).append(loader);
		},

		searchbarChange: function() {
			//do nothing if we are locked
			if (priv.searchbarLock) {
				return;
        }
			priv.setSearchbarLock();

			var selectedNValues = [];

			var occupancy = $('#reisgezelschap1').val();
			if (occupancy != null && occupancy != Occupancy.getOccupancy()) Occupancy.saveTotalTravelers(occupancy);

			selectedNValues.push($('#airport').val());
			selectedNValues.push($('#destination').val());
			selectedNValues.push($('#reisduur').val());
			selectedNValues.push($('#accommodatiesoort').val());
			selectedNValues.push($('#verzorging').val());
			selectedNValues.push($('#vervoer').val());
			selectedNValues.push($('#vertrekmaand').val());


			var filteredNValues = [];
			for (var i = 0; i < selectedNValues.length; i++) {
				if (selectedNValues[i] && selectedNValues[i] != -1) {
					filteredNValues.push(selectedNValues[i]);
				}
			}

			var loadcontrol = "~/controls/home/searchbar.ascx";

			$.ajax({
				// hack (Alexander): make a sync AJAX request.
				// Under some conditions an unknown handler executes right after this $.ajax call, 
				// but before result is received and parsed, and redirects to the wrong page.
				// The bug is that in FF on test server when on search page you filter by date with datePicker,
				// after filtering by e.g. destination, search result is incorrect
				// and query string in browser is ?unknown instead of ?N=0+... which probably corresponds to the line below:
				// location.href = currentLocation + '?' + $("#queryString").val();
				// async: false helps, because in this case that evil handler does not get an opportunity to execute.
				// As soon as race condition is fixed, async: false should be removed.
				async: true,
				url: Resource.GetText('path_prefix') + "/js/ajax/getcontrol.aspx",
				data: "N=" + filteredNValues.join('+') //todo
						+ "&loadControl=" + encodeURI(loadcontrol)
				,
				cache: false,
				success: function(result) {
					$('#searchbar').replaceWith(result);
					priv.bindSearchbarEvents();

					//unlock
					priv.searchbarLock = false;

				}
			});
		}
    };

    /** @scope Main */
    return {

        /**
         * Initializes the logic for the current page
         * to be called on $(document).ready
         */
		OnReady: function() {
            priv.initializeBannerpool();
            priv.bindPromoEvents();
            priv.bindSearchBoxEvents();
            priv.top10Tooltip();
            priv.bindPromoBlockEvents();

			priv.bindSearchbarEvents();
        }
    };
} (jQuery);
