﻿/**
 * static object that handles page logic for static pagess
 * @class
 * @constructor
 * @param {jQuery} $ Reference to the jQuery object
 */
var StaticMain = function($){
    
    /**
     * @namespace Private methods and variables
     */
    var priv = {
    
        /**
         * Set up the javascript functionality for the brochure request form
         * @private
         */
        setupBrochureForm: function () {
            $("#mag-street").before("<select id=\"dd-mag-street\"></select>");

            var formValidator = new Validator.Wrappers.FormValidation($('form#order-brochure'), ['brochure']);
            $("#btn-brochure").bind("click", function() {
				priv.toggleEmailRequired(formValidator);
			});
        },

        /**
         * Set up the javascript functionality for the cancellation form
         * @private
         */
        setupCancellationForm: function () {
            $("#vraagallereizigers").hide();
            $("#antwoordallereizigers").hide();
            
            $("#sendCancellationContent table input[name=allereizigers]").bind("click", function () {
                Cancellation.toggleTravelers(this);
            });
            
            $("#sendCancellationContent table input[type=button]").bind("click", function () {
                Cancellation.send();
            });
        },
        
        /**
         * Set up the javascript functionality for the company info ('about sunweb') page
         * @private
         */
        setupCompanyInfo: function () {
            $('#sendEmailLink').bind('click', function(){
                Utils.newWindow(this, 800, 640);
                return false;
            });
        },

        /**
        * Set up the javascript functionality for the bustrip info page (busreis.html)
        * @private
        */
        setupShowMap: function() {
        $('.showmap-link').bind('click', function() {
                Utils.newWindow(this, 475, 400);
                return false;
            });
        },
        
        /**
         * Setup javascript functionality for the group travel form
         * @private
         */
        setupGroupTravelForm: function () {
            $(".form-list input[type=button]").bind("click", function () {
                GroupTravel.submitForm();
            });
            
            $("form[name=formulier] input").bind('change', function () {
                return GroupTravel.Check(this);
            });
            
            $("form[name=formulier] select").bind('change', function () {
                if ($(this).attr("name") == "depdatum_maand" || $(this).attr("name") == "depdatum_jaar") {
                    return GroupTravel.Check($("form[name=formulier] select[name=depdatum_dag]").get(0));
                }

                return GroupTravel.Check(this);
            });
        },
        
        /**
         * Set up the javascript functionality for the prebooking form
         * @private
         */
        setupPrebookingForm: function () {
            $("#sendprebookContent input[type=button]").bind("click", function () {
                Prebooking.send();
            });
            $("#prebook-nrpersons").bind("change", function () {
                Prebooking.showCompanions($(this).val());
            });
        },
		
		/**
		 * Toggle whether the email input field is required
		 * @param {FormValidation} formValidator The form validator object that can be used to toggle a certain field to required
		 * @private
		 */
		toggleEmailRequired: function (formValidator) {
            if ($('#mag-agree').attr("checked")) {
                formValidator.setRequired("email");
                $('#mag-emailmandatorysymbol').show();
            } else {
                formValidator.setNotRequired("email");
                $('#mag-emailmandatorysymbol').hide();
                var msg = $("#mag-email").next(".errorText").text();
                if ($(".form-close .errorText").text() == msg) {
                    $(".form-close .errorText").hide();
                }
            }
        },

        successContact: function(result) {
            window.location = Resource.GetText("path_prefix") + '/_static/sendSuccess.aspx?type=contact&sexe=' + result;
        },

        errorContact: function(result) {
            priv.showContactError('Ein Fehler ist aufgetreten.');
        },

        showContactError: function(errorMsg) {
            priv.sendContactClicked = false;
            $('#contact-send-errormsg').show();
            $('#contact-send-errormsg').html(errorMsg);
            logic.CorrectShades();
        },

        showSendReactionError: function(errorMsg) {
            priv.sendReactionClicked = false;
            $('#sendreaction-errormsg').show();
            $('#sendreaction-errormsg').html(errorMsg);
            logic.resizePopup();
        },

        successSendReaction: function(result) {
            // reset input boxes
            $('#reaction-txtMessage').val('');
            $('#reaction-txtFromName').val('');
            $('#reaction-txtFromEmail').val('');
            $('#sendReactionContent').hide();
            $('#sendReactionMessage').show();
            logic.resizePopup();
        },

        errorSendReaction: function(result) {
            priv.showSendReactionError('Ein Fehler ist aufgetreten.');
        },
        
        sendContact : function () {
            //priv.sendContactClicked = true;
            $("#btnSendContact").bind("click", function(){
	            var sexe = $('#contact-sexe').val();              // * verplicht
	            var title = $('#contact-title').val();           
	            var firstletter = $('#contact-firstletter').val();  // * verplicht
	            var lastname = $('#contact-lastname').val();        // * verplicht
	            var birthday = $('#contact-birthday').val(); 
	            var birthmonth = $('#contact-birthmonth').val(); 
	            var birthyear = $('#contact-birthyear').val(); 
	            var street = $('#contact-street').val();            
	            var streetnr = $('#contact-streetnr').val();        
	            var postal = $('#contact-postal').val();            
	            var city = $('#contact-city').val();                
	            var country = $('#contact-country').val();          
	            var phoneprivate = $('#contact-phoneprivate').val();
	            var email = $('#contact-email').val();             // * verplicht
	            var bijzonderheden = $('#contact-bijzonderheden').val();
	            var agree = $('#contact-agree')[0].checked;
    	        
	            var reg = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	            var correctEmail = reg.test(email);
    	        
	            if(title == '0') {
	                priv.showContactError('Bitte geben Sie die Anrede ein!');
	            } else if(firstletter == '') {
	                priv.showContactError('Bitte geben Sie den Vornamen ein!');
	            } else if(lastname == '') {
	                priv.showContactError('Bitte geben Sie den Nachnamen ein!');
	            } else if(!correctEmail) {
	                priv.showContactError('Die E-Mail-Adresse entspricht nicht dem gültigen Format.');
	            } else {
	                // everything ok
    	            
	                $('#btn-brochure').attr('disabled',true);
	                $.ajax({
		                type: "POST",
		                url: Resource.GetText("path_prefix") + '/utilpages/addcontact.ashx',
			            data:   'title='+title+
			                    '&sexe='+sexe+
			                    '&firstletter='+firstletter+
			                    '&lastname='+lastname+
			                    '&birthday='+birthday+
			                    '&birthmonth='+birthmonth+
			                    '&birthyear='+birthyear+
			                    '&street='+street+
			                    '&streetnr='+streetnr+
			                    '&postal='+postal+
			                    '&city='+city+
			                    '&country='+country+
			                    '&phoneprivate='+phoneprivate+
			                    '&email='+email+
			                    '&agree='+agree+
			                    '&remarks='+bijzonderheden,
			            async: true,
        				
		                success : priv.successContact(sexe),
			            error : priv.errorContact
		            });
	            }
            });
        }
    };
    
    /**
     * Map pages to their respective setup methods
     */
    var config = {
        'html-busreis': priv.setupShowMap,
        'html-bedrijfsinfo': priv.setupCompanyInfo,
        'html-brochure': priv.setupBrochureForm,
        'static-prebooking': priv.setupPrebookingForm,
        'static-grouptravel': priv.setupGroupTravelForm,
        'static-cancellationform': priv.setupCancellationForm,
        'html-contact': priv.sendContact
    };

    /** @scope StaticMain */
    return {
    
        /**
         * Initializes the logic for the current page
         * to be called on $(document).ready
         */
        OnReady: function(){
            // Execute the correct functions for this page, defined in the config variable, using the body class
            var pageFunc = config[$('body').attr('class')];
            if (typeof(pageFunc) != "undefined" && pageFunc != null) {
                pageFunc();
            }
        }
    };
}(jQuery);
