﻿/**
 * 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 = {

		searchbarSelectElement: 'form.vacancy-form select',
		promotionBlockListElement: 'div.block-list ul li.item, ul.hotels li.item',
		hotspotTt: '.hotspot .menu a.watisdit',
	    elizaMessageIndex : 0,
		path_prefix: Resource.GetText('path_prefix'),

		bindPromoEvents: function() {
			$(priv.promotionBlockListElement).hover(
                function() { $(this).addClass("hover"); },
                function() { $(this).removeClass("hover"); }
            ).bind("click",
                function() {
                	//redirect to the correct page
                	var url;
                	if ($(this).find('a').size() > 0) {
                		url = $(this).find('a').attr("href");
                	}

                	document.location.href = url;
                	//prevent event bubbling
                	return false;
                }
            );
		},
		
		bindMessageButtons: function(){
			// eliza message links
            $('#eliza-mail .liNext a').bind('click', HomeMain.nextElizaMail);
            $('#eliza-mail .liPrev a').bind('click', HomeMain.prevElizaMail);
		},

		hotspotTooltip: function() {
			//enable tooltips hotspots     
			$(priv.hotspotTt).each(function() {
				$(this).jHelperTip({
					trigger: "hover",
					source: "container",
					ttC: "#jHelperTipAttrContainer", /* tooltip Container*/ 
					dC: $(this).attr('rel'),
					autoClose: true,
					topOff: 20,
					leftOff: -30,
					initializeOnce: false
				});
			});
		},


		bindSearchbarEvents: function() {
			$(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-02.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/common/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 {

		nextElizaMail : function($linkBtn){
		    var $linkBtn = $('#eliza-mail .liNext a');
		    if(!$linkBtn.hasClass('disabled')){
                priv.elizaMessageIndex -= 1;
                if(priv.elizaMessageIndex == 0){
                    $linkBtn.addClass('disabled');
                } else {
                    $('#email-block .liPrev a').removeClass('disabled');
                }
                var showClass = $('#eliza-mail').attr('class');
                $("div.eliza-mail").load(priv.path_prefix + '/js/ajax/getcontrol.aspx'+ 
                    '?loadControl='+priv.path_prefix+encodeURI('/controls/home/elizamail.ascx')+
                    '&newIndex='+priv.elizaMessageIndex+
                    '&showClass='+showClass,
                    null,
                    function(){ 
                        $('#eliza-mail .liNext a').unbind().bind('click', HomeMain.nextElizaMail);
                        $('#eliza-mail .liPrev a').unbind().bind('click', HomeMain.prevElizaMail);
                    }
                );
            }
		},
		
		prevElizaMail : function($linkBtn){
		    var $linkBtn = $('#eliza-mail .liPrev a');
		    if(!$linkBtn.hasClass('disabled')){
                priv.elizaMessageIndex += 1;
                if(priv.elizaMessageIndex == (parseInt($('#hidNrMessages').val()) - 1)){
                    $linkBtn.addClass('disabled');
                } else {
                    $('#eliza-mail .liNext a').removeClass('disabled');
                }
                var showClass = $('#eliza-mail').attr('class');
                $("div.eliza-mail").load(priv.path_prefix + '/js/ajax/getcontrol.aspx'+ 
                    '?loadControl='+priv.path_prefix+encodeURI('/controls/home/elizamail.ascx')+
                    '&newIndex='+priv.elizaMessageIndex+
                    '&showClass='+showClass,
                    null,
                    function(){ 
                        $('#eliza-mail .liNext a').unbind().bind('click', HomeMain.nextElizaMail);
                        $('#eliza-mail .liPrev a').unbind().bind('click', HomeMain.prevElizaMail);
                    }
                );
            }
		},

		closeElizamail : function(){
		    $('#eliza-mail').removeClass('full');
		},	
			
		showElizaMail : function(){
		    $('#eliza-mail').hide();
		    $('#eliza-mail').addClass('full').show("normal");
		},
		
		toggleElizaMail : function(){
		    if($('#eliza-mail').hasClass('full')){
		        HomeMain.closeElizamail();
		    } else {
		        HomeMain.showElizaMail();
		    }
		},
		
		redirectToNewsletter : function(){
		    var emailTxt = $('#email').val();
		    location.href = 'nieuwsbrief?email=' + emailTxt;
		},
		/*
		* Initialize the logic for the current page
		* to be called on $(document).ready
		*/
		OnReady: function() {
			priv.bindPromoEvents();
			priv.hotspotTooltip();
			priv.bindMessageButtons();
			priv.bindSearchbarEvents();
			Main.bindViewedFavoritesEvents();

			$('#home-bottom-block .left .user-data').bind('click', function() {
				location.href = Resource.GetText('path_prefix') + '/profile/login.htm';
			});
		}
		
	};
} (jQuery);
