;ET.ENQUIRY = 
{
    $form: null,
    autoComplete: [],
    fieldMappings:
    {
        dayPhone: 'Phone',
        departureDate: 'Depart',
        returnDate: 'Return'
    },
    
    enquiryType: 'general-enquiry',
    
    plugins: [],
    
    init: function(formId)
    {
        var form_id =  formId || '#enquiryForm';
        this.$form = $(form_id);
        if(this.$form.length == 0) { return; }

        this.setupForm();
        this.setupValidation();
        this.setupAutoComplete(form_id);
        FCL.SIGNALS.send('ET.ENQUIRY', 'init');
    },
    
    /**
     * Look for sku in url anda if not found return 'null' for reporting purposes
     */
    getSku: function()
    {
        var url, sku;
        
        sku = $('#productSku');
        if($('#productSku').length > 0)
        {
            return sku.text(); 
        }
        
        try
        {
            url = window.location.pathname;
            sku = url.substring( url.lastIndexOf('-') ).match(/\d+/);
            
            if(sku == null)
            {
                return 'null';
            }
            
            return sku[0];
        }
        catch(e)
        {
            return 'null';
        }
    },
    
    setupForm: function()
    {
        // Setup defaults and hidden values
        this.$form.find('input[name="todaysDate"]').val(ET.DATETIME.todaysDate());
        this.$form.find('#en_departureDate').val(ET.DATETIME.tomorrowsDate());
        this.$form.find('#en_returnDate').val(ET.DATETIME.weekFromToday());        
        this.$form.find('#en_pageURL').val(window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.search);
        
        /**
         * Check for existence of "referringUrl" query string variable as if we are on portable enquiry form of
         * main enquiry page, then recording this page's url in the enquiry data is useless. In these instances
         * we want to know where they've come from and change the default value of #en_pageURL accordingly
         */
         
         if(ET.UTIL.getQueryVariable('referringUrl') !== '')
         {
             this.$form.find('#en_pageURL').val(ET.UTIL.getQueryVariable('referringUrl'));
         }

        // We load datepickers on document.ready as they barf in IE otherwise
        $(document).ready(function()
        {
            if(typeof(FAREINFO) === 'undefined') {
                // Date pickers (force return date to be after departure date)
                ET.ENQUIRY.$form.find('#en_departureDate').datepicker($.extend(ET.SETTINGS.datePicker, { minDate: 1}));
                ET.ENQUIRY.$form.find('#en_returnDate').datepicker($.extend(ET.SETTINGS.datePicker, { minDate: 2}));
            }
        });
        
        // Adjust return date relative to departure date on departure date change
        this.$form.find('#en_departureDate').bind('change', function(e) 
        {
            var toOffsetFromDate = ET.DATETIME.compareDates(new Date(), ET.DATETIME.stringToDate(ET.ENQUIRY.$form.find('#en_departureDate').val()));
            ET.ENQUIRY.$form.find('#en_returnDate').datepicker('option', 'minDate', toOffsetFromDate.days);
        });
        
        ET.FORMS.replaceSubmitButton(this.$form.find('.submitButton'));

        // Execute Plugins that should run on dom ready
        this.executePluginsInit();
    },
    
    
    setupValidation: function()
    {

        $.validator.addMethod('isValidDate', function(value, element, params) 
        {   
            return ET.DATETIME.isValidDate(value.substring(6,10), value.substring(3,5), value.substring(0,2) );
        }, $.format('Must be a valid date'));
        
        this.$form.validate(
        {
            rules: 
            {
                numberTravellers: 'required',
                firstName: 'required',
                lastName: 'required',
                phone: 'required',
                postCode:
                {
                    required: true,
                    minlength: 3,
                    maxlength: 4,
                    digits: true
                },
                email: 
                {
                    required: true,
                    email: true
                },
                departureDate:
                {
                    'isValidDate': true
                },
                returnDate:  
                {   
                    'isValidDate': true,
                    'departureArrivalDates': true
                }
            },
            
            messages: 
            {
                email: 
                {
                    email: 'Please enter a valid email address, example: you@yourdomain.com'
                }
            },

            invalidHandler: function(e, validator)
            {
               FCL.FORMS.invalidForm(e, validator, ET.ENQUIRY.fieldMappings);
            },

            submitHandler: function(form)
            {
                ET.ENQUIRY.$form.trigger('replaceSubmit');

                // Record enquiry type in Google Analytics
                ET.registerGAPageView({ path: ET.ENQUIRY.enquiryType });
 
                /**
                 * Add in form field to record this is a Tourism Media enquiry in case GA fails
                 * timestamp is included so GA stats can be matched up with enquiries
                 */
                if(ET.TM.isWithinThreeClicks() || ET.UTIL.getQueryVariable('tourismMediaTracking') == 'true')
                {
                    var timestamp = function() { d = new Date(); return d.getTime(); }();
                    if(ET.ENQUIRY.$form.find('input[name="tourismMediaEnquiry"]').length == 0)
                    {
                        ET.ENQUIRY.$form.append('<input type="hidden" name="tourismMediaEnquiry" value="" />');
                    }
                    ET.ENQUIRY.$form.find('input[name="tourismMediaEnquiry"]').val('Yes: ' + timestamp);
                    ET.TM.googleAnalyticsReporting(timestamp);
                }
                
                // Execute Plugins that should run before form is submitted
                ET.ENQUIRY.executePluginsSubmit();
                FCL.SIGNALS.send('ET.ENQUIRY', 'submit');

                var path = window.location.pathname;

                var enquirySuccessPage = '/company/contact-us/enquiry-success';

                // If a sku is found, request enquiry success page appending sku so product specific tracking code is executed
                $('document').ready(function(){
                    if (jQuery('#fareinfoEnquiryForm').length > 0)
                    {
                        // do nothing
                    }
                    else
                    {
                        var sku = (ET.ENQUIRY.getSku() != 'null') ? ET.ENQUIRY.getSku() : ET.UTIL.getQueryVariable('sku');
                        if(sku != '')
                        {
                            enquirySuccessPage = '/company/contact-us/enquiry-success&query=sku:' + sku;
                        }
                        ET.ENQUIRY.$form.field('forwardUrl', enquirySuccessPage);
                    }
                });
                var gimpUrl = ET.GIMP.processForm(ET.ENQUIRY.$form);

                // Portable (lightbox) enquiry form, enquiry page, product enquiry page and international flights enquiry -  send to enquiry success page
                if(ET.UTIL.getQueryVariable('consultantRecommendsEnquiry')!='true' &&
                    (path.indexOf('portable-enquiry-form') > -1
                        || path.indexOf('contact-us/enquiry') > -1
                        || path.indexOf('/product/') > -1
                        || path.indexOf('international-flights-enquiry') > -1
                        || path.indexOf('/flight-booking/') > 1)
                    )
                {
                    top.location.href = gimpUrl;
                    return false;
                }

                // Process via AJAX
                $.get(gimpUrl, function(data)
                {
                    if(data.indexOf('Enquiry Success') > -1)
                    {
                        ET.ENQUIRY.$form.slideUp()
                                               .after('<div />')
                                               .next()
                                               .hide()
                                               .addClass('formNotification success')
                                               .html(ET.SETTINGS.LANG.enquirySuccess);
                        setTimeout(function()
                        {
                            ET.ENQUIRY.$form.next().fadeIn('slow');

                            // Include page which has same tracking code as enquiry success page in hidden iframe

                            // Default is basic iframe version which is good for general enquiries (as no need to parse securequery tags)
                            var enquirySuccessPage = '/wps/wcm/myconnect/escape-travel/company/contact-us/enquiry-success-javascript-iframe.html';

                            // If a sku is found, request enquiry success page appending sku so product specific tracking code is executed
                            var sku = (ET.ENQUIRY.getSku() != 'null') ? ET.ENQUIRY.getSku() : ET.UTIL.getQueryVariable('sku');
                            if(sku != '')
                            {
                                var enquirySuccessPage = '/company/contact-us/enquiry-success&query=sku:' + sku;
                            }

                            ET.ENQUIRY.$form.after('<iframe frameborder="no" height="0" width="0" src="'+ enquirySuccessPage +'" class="hide"></iframe>');
                        },750);
                    }
                    else
                    {
                        ET.ENQUIRY.$form.before('<div />')
                                               .prev()
                                               .hide()
                                               .addClass('formNotification error')
                                               .html(ET.SETTINGS.LANG.enquiryFailure);
                        setTimeout(function() { ET.ENQUIRY.$form.prev().fadeIn('slow'); },750);
                    }
                });
                return false;
            }
        });
    },

    setupAutoComplete: function(form_id)
    {
        
        $form = $(form_id);
        _dests = 'all';
        _defaultCity = '';

        $.ajax({
            dataType: 'text',
            url: '/js/iatacodes.js',
            success: function(dataReturned) {
                ET.ENQUIRY.iataCodes = $.parseJSON(dataReturned);

                // Create autosuggest list with weighting
                $.each(ET.ENQUIRY.iataCodes,function(i, val){
                    var tmpName = val.split(' - ');
                    if(tmpName.length>1){
                       tmpName = tmpName[0] +' '+  val.match(/(\(\w{3}\))/)[1];
                    } else{
                        tmpName = val;
                    }
                    // All weight 0 (no bookable flights)
                    var weighting = 0;

                    /*
                     *  Customizable destinations 'all', 'bookable', 'non-bookable' or object { 'BNE' : 'Brisbane', 'SYD' : 'Sydney' }
                     */

                    if(typeof(_dests) === "string")
                    {
                        if( _dests="all" || (_dests="non-bookable" && weighting==0) )
                       {
                            ET.ENQUIRY.autoComplete.push(  { value: val, iata: i, name: tmpName, weight: weighting  }    );
                       }
                    }
                    else if(typeof(_dests) === "object")
                    {
                        if(typeof(_dests[i])!=='undefined')
                        {
                            ET.ENQUIRY.autoComplete.push(  { value: val, iata: i, name: _dests[i], weight: weighting  }    );
                        }
                    }
                });


                ET.ENQUIRY.sortAutoComplete();


                ET.ENQUIRY.setupHtmlAutoComplete($('#en_destinationCity'));
                ET.ENQUIRY.setupHtmlAutoComplete($('#en_departureCity'));
                
            }
        });
    },

    setupHtmlAutoComplete: function($destField)
    {
        if ($destField.length == 0) {
            return false;
        }
        if( _defaultCity !== '')
        {
            ET.ENQUIRY.$form.field('destCode',_defaultCity);
            $destField.val( ET.ENQUIRY.iataCodes[_defaultCity].split('-')[0] );
        }
        else if($destField.val()==='' || $destField.val()==='Loading location...' )
        {
            $destField.val('Type location here...');
        }

        // Set default value behaviour
        $destField.focus(function(){
            this.select();

        }).focus(
            function(){
                if($(this).val()==='Type location here...')
                {
                    $(this).val('');
                }
            }
        ).blur( function(){
            if($(this).val()===''){
                $(this).val('Type location here...');
            }
            var searchDest =  { value: null, name: this.value, search: this.value } ;
            ET.ENQUIRY.checkDestination(searchDest);
        }).change( function(){
            ET.ENQUIRY.$form.field('destCode', '');
        });
        lilengthcount = 0;
        // setup autcomplete on document.load
        $destField.autocomplete(
        {
            minLength: (ET.ENQUIRY.autoComplete.length >20) ? 3 : 0,
            delay: 200,
            source: ET.ENQUIRY.autoComplete,
            select: function( event, ui ) {
                $destField.val( ui.item.name );
                var searchDest =  { value: ui.item.iata, name: ui.item.name, search: ui.item.value } ;
                ET.ENQUIRY.checkDestination(searchDest);
                return false;
            }
        }).data( 'autocomplete' )._renderItem = function( $ul, item ) {
           // This _renderItem function highlights the searched text and brings results matched at character 0 to the top
            
            if (lilengthcount >= 10) {
                return false;
            }
            lilengthcount++;
            if($ul.find('li#matchedFromStartSeperator').length<1)
            {
                $ul.append( '<li id="matchedFromStartSeperator">&nbsp;</li>' );

            }

            if(item.name.toLowerCase().indexOf($destField.val().toLowerCase()) ===0)
            {
                $li = $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( $( "<a></a>" ).attr({title: item.label }).html(ET.ENQUIRY.hightlightSearch(item.name,$destField.val())) );
                $ul.find('li#matchedFromStartSeperator').before($li);
                return $li;
            }
            else
            {
                $li = $( "<li></li>" )
                    .data( "item.autocomplete", item )
                    .append( $( "<a></a>" ).html(ET.ENQUIRY.hightlightSearch(item.name,$destField.val())) );
                $ul.append($li);
                return $li;
            }
        };


        // Force checking of the booking when user presses enter.
        $destField.keyup(function(e){
             var keyCode = parseInt(e.which,10);
             if(keyCode ===13)
             {
                 if (e.preventDefault)
                {
                    e.preventDefault();
                }
                else
                {
                    e.returnValue = false;
                }

                ET.ENQUIRY.getDestinationCode($destField.val());
            }
        });
    },

    checkDestination: function(destData){
       if(destData.value===null){
           destData = this.getDestinationCode(destData.name);
       }
       this.$form.field;('destCode', destData.value);
    },

    hightlightSearch: function(s,t){
        var matcher = new RegExp("("+$.ui.autocomplete.escapeRegex(t)+")", "ig" );
        return s.replace(matcher, "<strong>$1</strong>");
    },

    getDestinationCode: function(destinationName){
        var _this = this;

        if(destinationName.length<3)
        {
            return false;
        }
        // Remove whitespace to clean up what the user entered.
        try{
            destinationName = destinationName.match(/^\s*([\w()]{3,})\s*$/)[1];
        } catch(e){
        }

        // Check if the input has been autopoluated by an Autosuggest result
        var testIATA = destinationName.match(/\(([\w()]{3})\)/);
        if(testIATA)
        {
            destinationName = testIATA[1];
        }

        // Check if user has entered a 3-digit IATA code (eg LAX)
        if(destinationName && destinationName.length===3 )
        {
            destinationName=destinationName.toUpperCase();
            if (typeof _this.iataCodes[destinationName] !== 'undefined'){
                return { value:destinationName, name:  _this.iataCodes[destinationName], search: _this.iataCodes[destinationName] };
            }
        }

        var searchLength = destinationName.length;

        // For cities where more than one airport is available we should use the 'all airports' code.
        // The IATA codes file has been formated such that this will be the airport code whose value (description) is the shortest in length
        var currentMatchLength = 1000;
        var currentMatch;

        // else check the name
        $.each( _this.iataCodes, function(i, IATA){

            if(IATA.substring(0,searchLength).toLowerCase() === destinationName.toLowerCase() ){

                var newMatchLength = IATA.length;
                if(newMatchLength<currentMatchLength){
                    currentMatchLength =newMatchLength;
                    currentMatch = { value: i, name:  IATA, search: IATA };
                }
            }
        });

        if(currentMatch!==null && typeof currentMatch!=='undefined')
        {
            return currentMatch;
        }
        return false;
     },

     /**
      * @description Takes the automcomplete list and sorts by weighting, and alphabetically.
      * @return {object} the sorted autocomplete.
      */
     sortAutoComplete: function(){

         this.autoComplete = this.autoComplete.sort(function(a,b){
            var compA = a.weight;
            var compB = b.weight;
            return (compA > compB) ? -1 : (compA < compB) ? 1 : 0;
         });
         return this.autoComplete;
     },

    successTracking: function()
    {
        $head = $('head');
        var priceDigits = '0.00';
        var timestamp = function() { d = new Date(); return d.getTime(); }();
        var generalEnquiry = true; 


        /*___  WEB TRENDS ___*/
        var template = '<meta name="{1}" content="{2}" />';
        var tx_iPrefix = '';
        var wtDefaults = 
        {
            'WT.pn': 'General Enquiry | Thank You',
            'WT.cg_n': 'General Enquiry',
            'WT.si_n': 'General Enquiry',
            'WT.pn_gr': 'General Enquiry',
            'WT.pn_fa': 'General Enquiry',
            'WT.si_x': '2',
            'WT.si_cs': '1',
            'WT.tx_i': '',
            'WT.tx_e': 'p',
            'WT.tx_u': '1',
            'WT.tx_id': '',
            'WT.tx_it': ''
        };

        // Use timestamp as unique code
        var tx_iCode = timestamp;
        
        // Check if product WT vars exist. If so use that, if not, use defaults
        if($head.find('meta[name="WT.pn"]').length == 0)
        {
            // Change tx_iPrefix as that's what the old Escape Travel site did
            tx_iPrefix = 'general';
            
            $.each(wtDefaults, function(key, val)
            {
                $head.append(ET.UTIL.format(template, key, val));
            });
        }
        else
        {
            generalEnquiry = false;
            // Change to digits only for product enquiry
            try
            {
                priceDigits = $head.find('meta[name="WT.tx_s"]').attr('content').match(/\d+/gm)[0] + '.00';
                $head.find('meta[name="WT.tx_s"]').attr('content', priceDigits);
                window.ysm_customData.segment_1A8GUUAOFJ40F6 = ET.UTIL.format('event=1,transId={1},currency=AUD,amount={2}', timestamp, priceDigits);
            }
            catch(e){}
        }
        
        // Set other vars for both general and product enquiries
        $head.find('meta[name="WT.tx_i"]').attr('content', tx_iPrefix + tx_iCode);
        $head.find('meta[name="WT.tx_id"]').attr('content', ET.DATETIME.convertUSFormat(ET.DATETIME.todaysDate(), '/'));
        $head.find('meta[name="WT.tx_it"]').attr('content', ET.DATETIME.timeHHMMSS());
        
        // If AJAX driven enquiry, change name="WT.si_x" to 1 as it's not a 2 step process (as it is with success page)
        if(window.location.href.indexOf('enquiry-success-javascript-iframe.html') > -1)
        {
            $('head meta[name="WT.si_x"]').attr('content', '1');
        }
        
        
        /*___  GOOGLE TRACKING FROM E-CHANNEL ___*/
        var eChannelImages = [];
        if(generalEnquiry)
        {
            // General enquiry
            eChannelImages = [
                '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1031823632/?label=wkpgCLiikQEQkMKB7AM&amp;guid=ON&amp;script=0" class="hide"/>',
                '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1024428046/?label=sYEUCKrU0gEQjpC-6AM&amp;guid=ON&amp;script=0" class="hide"/>'
            ];
        }
        else
        {
            // Product enquiry
             eChannelImages = [
                '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1031823632/?label=IiRoCJKjkQEQkMKB7AM&amp;value=&amp;guid=ON&amp;script=0" class="hide"/>',
                '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1024428046/?label=wjaUCKLV0gEQjpC-6AM&amp;guid=ON&amp;script=0" class="hide"/>'
            ];
        }
        // Prepend is done as if you use append it barfes in IE (because this code is executed before the entire body has been parseed)
        $.each(eChannelImages, function(i)
        {
            $('body').prepend(eChannelImages[i]);
        });
        
        /*___ DGM TRACKING ___*/
        var dgm1 = '<img height="1" width="3" src="http://www.s2d6.com/x/?x=a&amp;h=58481&amp;o={1}" alt="" class="hide" />';
        var dgm2 = '<img height="1" width="3" src="http://www.s2d6.com/x/?x=r&amp;h=58481&amp;o={1}&amp;g=534388815258&amp;s={2}&amp;q=1" class="hide" />';
        $('body').prepend(ET.UTIL.format(dgm1, timestamp))
                 .prepend(ET.UTIL.format(dgm2, timestamp, priceDigits));    

        //Event tracking

        ET.TRACKING.trackEvent = {
            'action': 'enquiry',
            'typeOfEnquiry': 'email'
        };

        ET.TRACKING.eventTracking();
    },
    
    /**
     * Simple little function which adds a plugin to the plugins variable. This provides a simple way
     * for plugins to be registered that do things to the page and/or enquiry form when a certain 
     * condition is met
     */    
    registerPlugin: function(obj)
    {
        this.plugins.push(obj);
    },
    
    /**
     * Now that DOM is ready, run all the plugins so they can modify what they need to 
     */
    executePluginsInit: function()
    {
        $(document).ready(function()
        {
            for(var i=0; i<ET.ENQUIRY.plugins.length; i++)
            {
                try
                {
                    ET.ENQUIRY.plugins[i].init();
                }
                catch(e){}
            }
        });
    },
    
    executePluginsSubmit: function()
    {
        for(var i=0; i<ET.ENQUIRY.plugins.length; i++)
        {
            try
            {
                ET.ENQUIRY.plugins[i].submit();
            }
            catch(e){}
        }
    }
}; 
ET.ENQUIRY.init();


/***********************
*   REGISTER PLUGINS   *
***********************/

/*___ PRODUCT ENQUIRY ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        var sku, productDescription, productPrice, productSummary;
        /**
         * If this is a product enquiry, change enquiry type and create custom forwardUrl w
         * with sku appended to it so correct reporting can be done on enquiry success page
         * or in ajax processing
         */
        sku = ET.ENQUIRY.getSku();
        if(sku == 'null')
        {
            return;
        }
        
        // Set sku
        ET.ENQUIRY.$form.find('#en_sku').val(sku);
        
        // Get description and price
        productDescription = $.trim($('#productContainer h1:first').html());
        productPrice = $.trim($('#productLeftColumn .price:first').text());
        productSummary = productDescription + ' ' + productPrice;
                
        // Append product summary text to form title
        $('#enquiryForm .blueTitle h2').append(' - ' + productSummary);

        // Change enquiry type (reflected in Google Analytics stats)
        ET.ENQUIRY.enquiryType = 'product-enquiry/' + sku;
        
        // Change forwardUrl so it appends sku (required for product enquiry tracking)
        var skuForwardUrl = ET.SETTINGS.GIMP.forwardUrl + '&query=sku:' + sku;
        ET.ENQUIRY.$form.append('<input type="hidden" name="forwardUrl" value="'+ skuForwardUrl +'" />');
    },
    
    submit: function(){}
});
        

/*___ HONEYMOON ENQUIRIES ___*/
ET.ENQUIRY.registerPlugin(
{
    /**
     * If on any type of honeymoon related page, specify the ET.Honeymoon keyword
     * so the enquiry gets sent to a honeymoon specialist and change the title of
     * the enquiry form so it looks specific to honeymoons
     */
    init: function()
    {   
        var path = window.location.pathname;
        if(path.indexOf('honeymoon') == -1)
        {
            return;
        }
        
        // Change enquiry type (reflected in Google Analytics stats
        ET.ENQUIRY.enquiryType = 'honeymoon-enquiry';

        $('#enquiryForm .blueTitle h2').append(' - Your Honeymoon');
        if($('#enquiryForm input[name="keyWords"]').length > 0) 
        {
            var $keywords = $('#enquiryForm input[name="keyWords"]');
            $keywords.val(keywords.val() + ', ET.Honeymoon');
            return;
        }

        $('#enquiryForm').prepend('<input name="keyWords" id="en_keywords" type="hidden" value="ET.Honeymoon" />');
    },
    
    submit: function(){}
});

/*___ SEARCH RESULTS ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        /**
         * If this is a search results page and no product results were found
         * a generic enquiry form is shown, pre-populate destination
         */
        
        if(!ET.RESULTS)
        {
            return;
        }
        //
        if(!ET.RESULTS.checkForResults()){
            
           searchParams = ET.RESULTS.getSearchParameters();
           ET.ENQUIRY.$form.find('#en_destinationCity').val(searchParams.destination); 
           ET.FORMS.inputTextShowHide($('#en_firstName'));
           ET.FORMS.inputTextShowHide($('#en_lastName'));
        }
    },
    
    submit: function(){}
});

/*___ EVENT ENQUIRIES ___*/
ET.ENQUIRY.registerPlugin(
{
    /**
     * We add a hidden field for event enquiries to help the consultant when contacting the customer
     */
    init: function()
    {   
        var path = window.location.href;
        if(path.indexOf('event_title') == -1)
        {
            return;
        }
        
        var event_title = ET.UTIL.getQueryVariable('event_title');
        
        // Change enquiry type (reflected in Google Analytics stats
        ET.ENQUIRY.enquiryType = 'event-enquiry/' + event_title;

        $('#enquiryForm .blueTitle h1').append(' - ' + event_title);
        $('#en_pageURL').after('<input name="eventTitleEnquiry" id="en_eventTitleEnquiry" type="hidden" value="'+ event_title +'" />');
    },
    
    submit: function(){}
});


/*___ SIDEBAR ENQUIRY FORM ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function() {},

    submit: function()
    {
        if(ET.ENQUIRY.$form.find('input[name="sidebarEnquiryForm"]').length == 0)
        {
            return;
        }

        /**
         * All enquiry forms apart from product and round the world use the same GIMP
         * email template. This is fine except if a $templateVariable$ defined in this
         * template is not submitted, GIMP leaves it in the email to the consultant as
         * $templateVariable$. This doesn't look real cool.
         *
         * Therefore, the below adds the fields that are in the generalEnquiry email template
         * as hidden fields at the bottom of the form with empty values which ensures the
         * email template won't contain $departureCity$ for example
         */
         
        var extraFields = ['departureCity', 'destinationCity', 'numberTravellers', 'phone'];
        var template = '<input type="hidden" name="{1}" value="" />';
        
        for(var i=0; i<extraFields.length; i++)
        {
            ET.ENQUIRY.$form.append(ET.UTIL.format(template, extraFields[i]));
        }
    }
});


/*___ QUEEN MARY2 CRUISE ENQUIRY FORM ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        if(window.location.pathname.indexOf('queen-mary') == -1 && window.location.href.indexOf('queenMaryEnquiry') == -1)
        {
            return;
        }
        
        var path = window.location.href;

        // prepend "queenMaryEnquiry" query string var in prettyPhoto portable enquiry form href on landing page
        if(path.indexOf('portable-enquiry-form') == -1)
        {
            var portableLink = $('#emailConsultantSidebarLink').attr('href');
            $('#emailConsultantSidebarLink').attr('href', portableLink.replace(/\?/, '?queenMaryEnquiry=true&'));
        }
        
        // Put show/hide text on postal address focus
        ET.FORMS.inputTextShowHide(ET.ENQUIRY.$form.find('#en_postalAddress'));

        // Append - Queen Mary in form title display and append GIMP keyword "ET.QueenMary"     
        ET.ENQUIRY.$form.find('.blueTitle h2').append(' - Queen Mary');
    },
    
    submit: function(){}
});

/*___ YOUR CONSULTANTS RECOMMENDS ENQUIRY FORM ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        var search = window.location.search;
        if(search.indexOf('your-consultant-recommends') == -1 && search.indexOf('consultantRecommendsEnquiry') == -1)
        {
            return; 
        }
        
        var path = window.location.href;
        
        var URLvars = ET.UTIL.getUrlVars();
  
        // Append - in form title display and append GIMP keyword "ET.QueenMary"     
        ET.ENQUIRY.$form.find('.blueTitle h1').append(' - '+ URLvars['productSummary']);
        
        ET.ENQUIRY.$form.find('#en_firstName').val(URLvars['ufname']);
        ET.ENQUIRY.$form.find('#en_lastName').val(URLvars['usname']);
        ET.ENQUIRY.$form.find('#en_phone').val(URLvars['umobile']);
        ET.ENQUIRY.$form.find('#en_email').val(URLvars['uemail']);
        ET.ENQUIRY.$form.find('#en_postcode').val('0000');
        var template = '<input type="hidden" name="GIMP_route" value="ET.'+URLvars['pseudo']+ '" />';
        
        ET.ENQUIRY.$form.find('#en_enquiryType').val('Consultant Recommends');
        ET.ENQUIRY.$form.find('#en_subject').val("Attn: "+URLvars['fname']+" "+URLvars['sname']+" - {enquiryType} Enquiry: {firstName} {lastName} ({email})");
        ET.ENQUIRY.$form.append(template);
         /*  
         *   Check for SKU and determine whether this will be a general enquiry or a product enquiry
         *
        */
        var sku = URLvars['sku'];
        // Set a custom enquirySuccess message
        ET.SETTINGS.LANG.enquirySuccess = "Thanks for your enquiry. I will be in contact with you shortly to discuss your travel needs.";
        // Set a custom enquiryFailuire message
        ET.SETTINGS.LANG.enquiryFailure = "We were unable to send your enquiry at this time. Please contact " + URLvars['fname'] + " " + URLvars['sname'] +" directly on " + URLvars['phone'].match(/(\d{4})\D*(\d{3})\D*(\d{3})/).slice(1,4).join(' ') + ".";
     

        if(sku != null){
            
            // Change enquiry type (reflected in Google Analytics stats)
            ET.ENQUIRY.enquiryType = 'my-portfolio/sku:' + sku;
            
            ET.ENQUIRY.$form.find('#en_template').val('etau/productEnquiry');
            ET.ENQUIRY.$form.find('#en_bbTemplate').val('etau/bb-productEnquiry');
            var skuField = '<input type="hidden" name="sku" id="en_sku" value="'+sku+ '" />';
            ET.ENQUIRY.$form.append(skuField);
            var productField = '<input type="hidden" name="productSummary" id="en_productSummary" value="'+URLvars['productSummary']+ '" />';
            ET.ENQUIRY.$form.append(productField);
            
        }

    },
    
    submit: function(){}
});

/*___ PRODUCT ENQUIRY FORM ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        var search = window.location.search;
        if(search.indexOf('productEnquiry=true') == -1 )
        {
            return; 
        }
        
        var URLvars = ET.UTIL.getUrlVars();
        var sku = URLvars['sku'];
        var productSummary = URLvars['productSummary'];
  
        // Append product summary to enquiry form title.    
        ET.ENQUIRY.$form.find('.blueTitle h1').append(' - '+productSummary );
        
        // Hide unrequired fields to make more like product form
        $('#preferredMethodContactContainer').css({'display': 'none'});
        $('#en_destinationCity').parent().css({'display': 'none'});
        /*  
        *    Check for SKU and determine whether this will be a general enquiry or a product enquiry
        */
        var sku = URLvars['sku'];

        if(sku != null){
            // Change enquiry type (reflected in Google Analytics stats)
            ET.ENQUIRY.enquiryType = 'product-enquiry/' + sku;
            ET.ENQUIRY.$form.find('#en_enquiryType').val('Product Enquiry');
            ET.ENQUIRY.$form.find('#en_template').val('etau/productEnquiry');
            ET.ENQUIRY.$form.find('#en_bbTemplate').val('etau/bb-productEnquiry');
            var skuField = '<input type="hidden" name="sku" id="en_sku" value="' +sku+ '" />';
            ET.ENQUIRY.$form.append(skuField);
            var productField = '<input type="hidden" name="productSummary" id="en_productSummary" value="'+productSummary+ '" />';
            ET.ENQUIRY.$form.append(productField);
            
        }
    },
    
    submit: function(){
        
        ET.ENQUIRY.$form.find('#en_freeText').val( );
    
    }
});

/*___ TRAVEL INDO CHINA / FREE DVD FORM : 22-09-2010 ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        var path = window.location.pathname;
        if(path.indexOf('vipdeals') == -1)
        {
            return;
        }
        
        // Validation
        ET.ENQUIRY.$form.find('input[name="address"]').rules('add', 'required');
        ET.ENQUIRY.$form.find('input[name="city"]').rules('add', 'required');
        ET.ENQUIRY.$form.find('select[name="state"]').rules('add', 'required');     
        ET.ENQUIRY.enquiryType = 'travel-indo-china-dvd';
        
        // remove datepicker calendars
        ET.ENQUIRY.$form.find('#en_departureDate').datepicker('destroy');
        ET.ENQUIRY.$form.find('#en_returnDate').datepicker('destroy');
        
        $('#enquiryForm').prepend('<input name="keyWords" id="en_keywords" type="hidden" value="freedvdindochina" />');

    },
    
    submit: function(){
        ET.SETTINGS.LANG.enquirySuccess="Your submission has been sent.";
    }
    
});

/*___ SEM ENQUIRY for FLIGHTS & HOLIDAYS : 13-10-2010 ___*/
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        var path = window.location.pathname;
        if(path.indexOf('sem-enquiry') == -1)
        {
            return;
        }

        // Validation

        ET.ENQUIRY.$form.find('select[name="preferredContact"]').rules('add', 'required');
        ET.ENQUIRY.enquiryType = 'sem-enquiry';

        // populate product summary
        if(path.indexOf('sem-enquiry/flights') != -1)
        {
            ET.ENQUIRY.productSummary = 'Flights Enquiry (from a search engine)';    
        }
        if(path.indexOf('sem-enquiry/holidays') != -1)
        {
            ET.ENQUIRY.productSummary = 'Holidays Enquiry (from a search engine)';    
        }

    },

    submit: function(){
        ET.SETTINGS.LANG.enquirySuccess="Your submission has been sent.";
    }

});

//plugin to register any user that checks the emailNewsletter check box
//if the user is already registered then we do nothing.
ET.ENQUIRY.registerPlugin(
{
    init: function()
    {},

    submit: function()
    {
        var $newsletterField = ET.ENQUIRY.$form.find('input[name=emailNewsletter]:checked');
        if(typeof($newsletterField) !== 'undefined' && $newsletterField.val() == 'Yes')
        {
            var email = ET.ENQUIRY.$form.find('input[name=email]').val();
            var fullName = ET.ENQUIRY.$form.find('input[name=firstName]').val() + " " + ET.ENQUIRY.$form.find('input[name=lastName]').val();
            var phone = ET.ENQUIRY.$form.find('input[name=phone]').val();
            var postCode = ET.ENQUIRY.$form.find('input[name=postCode]').val();
            var source= '10011'; //website see doc for more source id's
            var key = 'badc6f3110f28125570bcd5564fcf154';

            $.ajax({
                url: '/fcl/js/fcl/fcl.xcomm.js?',
                dataType: 'script',
                async:false,
                success:function(data){
                    FCL.UTIL.xcommSubscribe(email,fullName,phone,postCode,source,key);
                }
            });

        }
    },
    name: 'emailNewsletter'
});

/**
 * Fareinfo plugin.
 */

ET.ENQUIRY.registerPlugin(
{
    init: function()
    {
        var path = window.location.pathname;
        if(path.indexOf('flight-booking') == -1)
        {
            return;
        }
        var $form = ET.ENQUIRY.$form;
        $(document).ready(function(){
            FCL.FORMS.replaceSubmitButton($form.find('.enquiry-form-submit'),'/images/general/waiting.gif');
            if (FCL.UTIL.getUrlVar('depDate') != '') {
                $form.find('input[name="departureDate"]').val(FCL.UTIL.getUrlVar('depDate'));
            }
            if (FCL.UTIL.getUrlVar('retDate') != '') {
                $form.find('input[name="returnDate"]').val(FCL.UTIL.getUrlVar('retDate'));
            }
        });
    },

    submit: function()
    {
        var path = window.location.pathname;
        if(path.indexOf('flight-booking') == -1)
        {
            return;
        }


        /*
         *  Before submit we need to populate the enquiry form with the values from the users selection
         */
        var $form = ET.ENQUIRY.$form;
        $form.trigger('replaceSubmit');

        var fare = FAREINFO.selectedFlight,
            itinerarySeperator = '.\n  ',
            itinerary = '',
            _departureCityCode = '',
            _departureCityName = '',
            _departureCityCountryName = '',
            _departureString = '',
            _arrivalCityCode = '',
            _arrivalCityName = '',
            _arrivalCityCountryName = '',
            _arrivalString = '',
            _cabinClass = '',
            _fareType = '',
            _routeType = '',
            _enquiryType = '',
            _airlineName = '',
            _airlineCode = '',
            _price = 'N/A',
            _base = '',
            _tax = '',
            _specialID = 'No Fare';
        
        if(typeof(FAREINFO.modelJson)!=='undefined' && FAREINFO.modelJson!==null) {
            _departureCityCode = (typeof(FAREINFO.modelJson.responseJson.journey.departureCity.code)!='undefined') ? FAREINFO.modelJson.responseJson.journey.departureCity.code : 'no-results';
            _departureCityName = (typeof(FAREINFO.modelJson.responseJson.journey.departureCity.name)!='undefined') ? FAREINFO.modelJson.responseJson.journey.departureCity.name : 'no-results';
            _departureCityCountryName = (typeof(FAREINFO.modelJson.responseJson.journey.departureCity.country.name)!='undefined') ? FAREINFO.modelJson.responseJson.journey.departureCity.country.name : 'no-results' ;
            _departureString = _departureCityName +' ('+_departureCityCountryName+')';
            
            _arrivalCityCode = (typeof(FAREINFO.modelJson.responseJson.journey.arrivalCity.code)!='undefined') ? FAREINFO.modelJson.responseJson.journey.arrivalCity.code : 'no-results';
            _arrivalCityName = (typeof(FAREINFO.modelJson.responseJson.journey.arrivalCity.name)!='undefined') ? FAREINFO.modelJson.responseJson.journey.arrivalCity.name : 'no-results';
            _arrivalCityCountryName = (typeof(FAREINFO.modelJson.responseJson.journey.arrivalCity.country.name)!='undefined') ? FAREINFO.modelJson.responseJson.journey.arrivalCity.country.name : 'no-results';
            _arrivalString = _arrivalCityName +' ('+_arrivalCityCountryName+')';
            
            _cabinClass = (typeof(FAREINFO.modelJson.cabinClass)!='undefined') ? FAREINFO.modelJson.cabinClass : 'no-results';
            _fareType = (typeof(FAREINFO.modelJson.fareType)!='undefined') ? FAREINFO.modelJson.fareType : 'no-results';
            _routeType = (typeof(FAREINFO.modelJson.routeType)!='undefined') ? FAREINFO.modelJson.routeType : 'no-results';
            _enquiryType = (typeof(FAREINFO.modelJson.responseJson)!=='undefined') ?  (FAREINFO.modelJson.responseJson.journey.departureCity.code + '-' + FAREINFO.modelJson.responseJson.journey.arrivalCity.code)  : 'no-results' ;
            
            if(typeof(fare)!='undefined') {
            // build Itinerary string
                $.each(fare.legs, function(i, leg)
                {
                    itinerary += leg.departureAirport.code + '-'
                              + leg.arrivalAirport.code + '-'
                              + leg.flightNumber +  '-'
                              + leg.departureTime +  '-'
                              + leg.arrivalTime + itinerarySeperator;
                });
                
                _airlineName = typeof(fare.airline.name)!='undefined' ? fare.airline.name : _airlineName;
                _airlineCode =  typeof(fare.airline.code)!='undefined' ? fare.airline.code : _airlineCode;
                _price = typeof(fare.price.grossPrice)!='undefined' ? '$' + fare.price.grossPrice : _price;
                _base = typeof(fare.price.nettPrice)!='undefined' ? '$' + fare.price.nettPrice : _base;
                _tax = typeof(fare.price.tax)!='undefined' ? '$' + fare.price.tax : _tax;
                
                // If this is an internal product report on the SKU
                _specialID = (fare.code=="SKU") ? fare.sku : fare.code;
                
                if(fare.code=="SKU")
                {
                     itinerary = 'sku product';
                }
            }
        } 
        if(typeof(FAREINFO.queryObj) !== 'undefined' && _departureCityCode === '') {
            _departureCityCode =  (typeof(FAREINFO.queryObj.depCode)!='undefined' ? FAREINFO.queryObj.depCode : _departureCityCode );
            _departureCityName = (typeof(FAREINFO.queryObj.depCity)!='undefined' ? FAREINFO.queryObj.depCity : _departureCityName );
            _departureString = (typeof(FAREINFO.queryObj.depStr)!='undefined' ? FAREINFO.queryObj.depStr : _departureString );

            _arrivalCityCode = (typeof(FAREINFO.queryObj.destCode)!='undefined' ? FAREINFO.queryObj.destCode : _arrivalCityCode );
            _arrivalCityName = (typeof(FAREINFO.queryObj.destCity)!='undefined' ? FAREINFO.queryObj.destCity : _arrivalCityName );
            _arrivalString = (typeof(FAREINFO.queryObj.destStr)!='undefined' ? FAREINFO.queryObj.destStr : _arrivalString );
            
            _cabinClass = (typeof(FAREINFO.queryObj.cabinClass)!='undefined' ? FAREINFO.queryObj.cabinClass : _cabinClass );
            _fareType = (typeof(FAREINFO.queryObj.fareType)!='undefined' ? FAREINFO.queryObj.fareType : _fareType );
            _routeType = (typeof(FAREINFO.queryObj.routeType)!='undefined' ? FAREINFO.queryObj.routeType : _routeType );
            _enquiryType = _departureCityCode + '-' + _arrivalCityCode;
            _airlineCode = 'N/A';
        }

        // Set the enquiry success message to be more informative
        ET.SETTINGS.LANG.enquirySuccess = 'Your international flights enquiry from '+ _departureCityName +' to '+ _arrivalCityName +' has been sent and a flights specialist will be in contact with you shortly. ';

        
                // Change enquiry-type (reflected in Google Stats)
        $form.field('enquiryType', 'international-flights-enquiry/' + _enquiryType);
        $form.field('specialOid', _specialID);
        
        // Populate general enquiry form feilds.
        $form.field('departureIATA', _departureCityCode );
        $form.field('departureCity', _departureCityName);
        $form.field('departureStr', _departureCityName);

        $form.field('destinationIATA', _arrivalCityCode);
        $form.field('destinationCity', _arrivalCityName);
        $form.field('destinationStr', _arrivalCityName);
        
        $form.field('cabinClass', _cabinClass);
        $form.field('fareType', _fareType);
        $form.field('tripType', _routeType);
        
        $form.field('airlineName', _airlineName);
        $form.field('airlineCode', _airlineCode);
        $form.field('price', _price);
        $form.field('base', _base);
        $form.field('tax', _tax);
        
        if(_routeType == 'OW') {
            $form.field('retDate', '');
        }
        $form.field('itin', itinerary);

        // Set the forwsrd URL for success tracking to include Fareinfo information
        var skuForwardUrl = ET.SETTINGS.GIMP.forwardUrl + '?product='+_departureCityCode+'+to+'+_arrivalCityCode+'&engine=fareinfo&supplier='+_airlineName+'&fareinfoid='+ _specialID + '&price='+_price;
        $form.field('forwardUrl', skuForwardUrl);
    }
});
