﻿// javascript for the quick enquiry process
// requires quickPopup.js and jQuery

// add text ghosting for quickEnquire form on page
jQuery(function () {

    // this is filled in later
    var setEvents = function () { };

    // can we cancel the popup (to prevent infinite loops)
    var canCancel = false;

    // display postback data
    var displayPostbackData = function (url, htmlStr) {
        var jHtml = jQuery(htmlStr);

        // if this is the advert page, simply replace the body and set any links
        if (jQuery('div#advertMain', jHtml).size() > 0) {

            // close the popup
            QuickPopup.cancel();

            // replace parts of the advert page and set display links
            jQuery.each(['div#header', 'div#advertTop', 'div.quickEnquirePanel'], function (i, v) {
                jQuery(v).replaceWith(jQuery(v, jHtml));
            });
        } else {

            // set popup text
            var jContent = jQuery('div#container', jHtml);

            // pull out title (if possible)
            var titleRegexResults = (new RegExp('<\s*title\s*>([^<]+)</\s*title\s*>')).exec(htmlStr);
            var title = (titleRegexResults != null) ? titleRegexResults[1] : 'Contact the seller';
            title = jQuery.trim(title.replace(/\s+/g, ' '));

            // change all ids to add 'popup' to the end
            jQuery('*', jContent).each(function (i, v) {
                if (jQuery(v).attr('id') != '') {
                    jQuery(v).attr('id', jQuery(v).attr('id') + '-popup');
                }
            });

            // get extra options (e.g. width)
            var extraOptions = {};
            if (jQuery('.hiddenContainerWidth', jContent).size() > 0)
                extraOptions['width'] = jQuery('.hiddenContainerWidth', jContent).text();

            // show popup, allow us to cancel popup
            QuickPopup.show(title, jQuery('div#container > *', jHtml), extraOptions);
            canCancel = true;
        }

        // make sure we set events to fire.
        setEvents();

        // track the page we've just loaded (if google analytics is present on primary page)
        if (window['pageTracker'] != undefined) {
            window['pageTracker']._trackPageview(url);
        }
    };

    // unbinds and rebinds any links for the given selector
    setEvents = function () {

        // live selectors
        var jSelector = jQuery('div.quickEnquirePanel, div#qp-overlay, form#contactSeller');

        // set ghost title focus and blur behaviour
        jQuery('form.hasGhostTitles :input[title]', jSelector)
            .unbind('focus')
            .unbind('blur')
            .focus(function (e) {
                var jt = jQuery(e.target);
                if (jt.is('.ghostTitle'))
                    jt.removeClass('ghostTitle').val('');
            })
            .blur(function (e) {
                var jt = jQuery(e.target);
                if ((jt.is('.ghostTitle')) || (jt.val() == '') || (jt.val() == jt.attr('title')))
                    jt.addClass('ghostTitle').val(jt.attr('title'));
            })
            .blur();

        // updates states list whenever the country changes
        jQuery('select[name="country"]', jSelector).unbind('change').change(function (e) {

            // get the form which contains this events
            var jCountry = jQuery(e.target);
            var jForm = jQuery(e.target.form);

            // pull out the states and reset the states part of the form
            jQuery.get('quickEnquire/statesForCountry.aspx', { countryID: jCountry.val() }, function (html) {
                var jState = jQuery('select[name="state"]', jForm);
                var oldVal = jState.val();

                // take out all non-null options
                jQuery('option[value!=""]', jState).remove();

                // add in all options if there are any, and disable / enable the control
                jState.append(jQuery('option', html));
                if (jQuery('option', html).size() > 1) {
                    jState.attr('disabled', '').val(oldVal);
                } else {
                    jState.attr('disabled', 'disabled').val('');
                }
            });
        });

        // every form should postback
        jQuery('input[type="submit"]', jSelector).unbind('click').click(function (e) {

            // pull out data
            var jForm = jQuery(e.target.form);
            var data = jForm.serialize();

            // clear title text ghosting (cleaner way of clearing on submit event doesn't work in IE)
            jQuery(':input.ghostTitle', jForm).each(function () {
                data = data.replace(new RegExp(jQuery(this).attr('name') + '=[^&]*', 'gim'), jQuery(this).attr('name') + '=');
            });

            // perform postback
            var url = jForm.attr('action');
            jQuery.ajax({
                'url': url,
                'data': data,
                'type': 'POST',
                'cache': false,
                'success': function (htmlStr) { displayPostbackData(url, htmlStr); },
                'error': function () { QuickPopup.error(); }
            });

            // don't bubble up
            return false;
        });

        // every link should post back.
        jQuery('a', jSelector).unbind('click').click(function (e) {
            var url = jQuery(e.target).attr('href');

            // returns true if the url contains a substring (case insensitive)
            var contains = function (u, s) { return (u.toLowerCase().indexOf(s.toLowerCase()) > -1); };

            // only perform any action on non-javascript links with quickEnquire in the url that aren't register.aspx
            if ((contains(url, 'quickEnquire') || contains(url, 'advert.aspx')) && !(contains(url, 'javascript') || contains(url, 'register.aspx'))) {

                // perform ajax request
                jQuery.ajax({
                    'url': url,
                    'type': 'GET',
                    'cache': false,
                    'success': function (htmlStr) { displayPostbackData(url, htmlStr); },
                    'error': function () { QuickPopup.error(); }
                });

                // don't bubble up
                return false;
            }
        });
    };

    // quickpopup cancel ajax-reloads the page (allow 1 second between postbacks);
    QuickPopup.cancel(function () {
        if (canCancel) {
            var rootUrl = window.location.href;
            jQuery.ajax({
                'url': rootUrl,
                'type': 'GET',
                'cache': false,
                'success': function (htmlStr) { canCancel = false; displayPostbackData(rootUrl, htmlStr); }
            });
        }
    });

    // set events initally
    setEvents();
});
