﻿jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

try {
    Type.registerNamespace("Address.Lookup");
}
catch (e) {
    if (typeof (console) !== 'undefined' && console != null)
        console.log(e);
}
Address.Lookup = function (_btnPrefix, _ddlJAddress, _validationGroup) {
    var me = this;
    this.btnPrefix = _btnPrefix;
    this.validationGroup = _validationGroup;
    this.validateByControl = false;
    this.btnFindAddress = null;
    this.btnJFindAddress = null;
    this.txtHouseNumber = null;
    this.txtPostcode = null;
    this.txtAddressLine1 = null;
    this.txtAddressLine2 = null;
    this.txtTown = null;
    this.txtCounty = null;
    this.pnlSelectAddress = null;
    this.ddlJAddress = _ddlJAddress;
    this.pnlSubscribeFormAddress = null;
    this.btnProcessing = null;
    // Remove our server control button
    this.ddlJAddress.change(function () {
        try {
            // Get the selected address
            Website.Resources.Code.Services.ADFLookupWebService.GetAddress($(this).find(':selected').val(), me.OnLookupComplete, me.OnError, me);
        }
        catch (e) {
            alert(e);
            showJsError('Sorry, our post code lookup service is currently unavailable, please manually enter your address below');
            btnJFindAddress.css('display', 'block');
            btnProcessing.css('display', 'none');
            pnlSelectAddress.css('display', 'none');
        }
    });
};

Address.Lookup.prototype = {
    createButton: function () {
        this.btnFindAddress.after('<input id="' + this.btnPrefix + 'btnJFindAddress" type="button" class="btnLookup" value="Look up Address" tabindex="' + this.btnFindAddress.attr("tabindex") + '"/>');
        this.btnJFindAddress = $('#' + this.btnPrefix + 'btnJFindAddress');
        var self = this;
        $(this.btnJFindAddress).click(function () {
            if (self.validateByControl) {
                if (typeof (ValidatorValidate) == 'function') {
                    var validator = $('#' + self.validationGroup)[0];
                    ValidatorValidate(validator);

                    if (validator.isvalid) {
                        self.OnLookup();
                    }
                }
            } else {
                if (typeof (Page_ClientValidate) == 'function') {

                    var validated = Page_ClientValidate(self.validationGroup);

                    if (Page_IsValid)
                        self.OnLookup();
                }
            }
        });
        this.btnFindAddress.css('display', 'none');
    },
    ValidatePostcode: function (sender, args) {
        var regEx = new RegExp('^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$');

        if (args.Value.match(regEx)) {
            args.IsValid = true;
        } else {
            args.IsValid = false;
        }
    },
    OnLookup: function () {
        // Performs the service request
        try {
            this.btnJFindAddress.css('display', 'none');
            this.btnProcessing.css('display', 'block');
            Website.Resources.Code.Services.ADFLookupWebService.FindAddress(this.txtHouseNumber.val(), this.txtPostcode.val(), this.OnLookupComplete, this.OnError, this);
        }
        catch (err) {
            alert(err);
            this.btnJFindAddress.css('display', 'block');
            this.btnProcessing.css('display', 'none');
            showJsError('Sorry, our post code lookup service is currently unavailable, please manually enter your address below');
        }
    },
    OnLookupComplete: function (result, context) {

        // Service callback
        context.btnJFindAddress.css('display', 'block');
        context.btnProcessing.css('display', 'none');
        // If we have more that 1 result user needs to select address
        if (result.Results.length > 1) {
            //show model popup if on new application form
            if ($('#appointmentForm2').length) {

                var postcode = context.txtPostcode.val();
                var regEx = new RegExp('^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$');

                if (postcode.length > 0 && postcode.match(regEx)) {
                    showModal();
                }
            }

            context.ddlJAddress.find('option').remove().end();

            var optionItem = '<option value="null" selected="selected">Please select...</option>';
            context.ddlJAddress.append(optionItem);

            for (var i = 0; i < result.Results.length; i++) {
                optionItem = '<option value="' + result.Results[i].PostKey + '">' + result.Results[i].Line + '</option>';
                context.ddlJAddress.append(optionItem);
            }
            // Show the select menu
            context.pnlSelectAddress.css('display', 'block');

            //move drop-down in to modal pop-up
            $('#postcodeLabel').remove();
            $('#address_ddlJAddress').appendTo('#postcodeLookup h3').attr('size', 8);
            $('#address_ddlJAddress option').css('padding-top', 5).css('padding-bottom', 5);
        }
        else {
            if (result.Results.length == 0) {
                showJsError('Sorry, we could not find any address details for the post code you entered, please review your entry or alternatively manually enter your address below');
                context.pnlSelectAddress.css('display', 'none');
            }
            else {
                if (result.Results[0].Organisation == null) {
                    try {
                        // Get the selected address
                        Website.Resources.Code.Services.ADFLookupWebService.GetAddress(result.Results[0].PostKey, context.OnLookupComplete, context.OnError, context);
                    }
                    catch (e) {
                        showJsError('Sorry, our post code lookup service is currently unavailable, please manually enter your address below');
                        context.pnlSelectAddress.css('display', 'none');
                    }
                }
                else {
                    // If we have just one address, fill out the fields and highlight
                    context.PopulateAddress(result.Results[0]);
                    context.pnlSubscribeFormAddress.find('.textField').effect("highlight", {}, 1000);
                    context.pnlSelectAddress.css('display', 'none');
                }
            }
        }
    },
    OnError: function (error, context) {
        showJsError('Sorry, our post code lookup service is currently unavailable, please manually enter your address below');
        context.btnProcessing.css('display', 'none');
    },
    PopulateAddress: function (data) {
        // Populate our address fields correctly
        var addr1 = '';
        var addr2 = '';

        if (this.txtHouseNumber.val().length == 0)
            this.txtHouseNumber.attr('value', data.Building);

        if (data.Organisation.length > 0) {
            if (data.Building.length > 0) {
                addr1 += data.Organisation + ", " + data.Building;
                addr2 += data.Street;
                if (data.Locality.length > 0) addr2 += ", " + data.Locality;
            }
            else {
                addr1 += data.Organisation + ", " + data.Street;
                addr2 += data.Locality;
            }
        }
        else if (data.Building.length > 0) {
            addr1 += data.Building;
            addr2 += data.Street;
            if (data.Locality.length > 0) addr2 += ", " + data.Locality;
        }
        else {
            addr1 += data.Street;
            addr2 += data.Locality;
        }

        this.txtAddressLine1.attr('value', addr1);
        this.txtAddressLine2.attr('value', addr2);
        this.txtTown.attr('value', data.Town);
        this.txtCounty.attr('value', data.County);
    }
};

try {
    Address.Lookup.registerClass('Address.Lookup');
} catch (e) {
    if (typeof (console) !== 'undefined' && console != null)
        console.log(e);
}

try {
    /***** Modal pop-ups for callback request ***/
    Type.registerNamespace("CallbackPopup");
} catch (e) {
    if (typeof (console) !== 'undefined' && console != null)
        console.log(e);
}

CallbackPopup = function () {
    var me = this;
    this.viewType = { 'CallbackModal': 0, 'CallbackForm': 1, 'CallbackComplete': 2 };
    this.screen = null;
    this.callbackForm = null;
    this.serviceUrl = 'http://' + document.location.hostname + (document.location.port == '80' ? '' : ':' + document.location.port) + '/Resources/Code/Services/EverestAPI.asmx';
    this.trackingHolder = $('#floodLightTrackingContainer');
};

CallbackPopup.prototype = {
    init: function () {
        if ($.cookie('state') && $.cookie('state') == 'completed')
            return false;

        _this = this;
        return true;
    },
    render: function (timeoutSeconds) {
        if (this.init()) {
            _this = this;

            $.ajax({
                context: this,
                type: "POST",
                data: '{ "timeoutSeconds": ' + timeoutSeconds + ' }',
                dataType: "json",
                url: this.serviceUrl + '/GetTimeout',
                contentType: "application/json; charset=utf-8",
                success: this.onInitSuccess,
                error: this.onError
            });
        }
    },
    onInitSuccess: function (output) {
        if (output.d > 0)
            setTimeout(function () { _this.renderModal() }, output.d);

        try { console.log(output.d); }
        catch (e) { ; }

        //setTimeout(function () { _this.renderModal() }, 10000);
    },
    renderModal: function () {
        $.ajax({
            context: this,
            type: "POST",
            data: '{ "viewType": ' + this.viewType.CallbackModal + ' }',
            dataType: "json",
            url: this.serviceUrl + '/RenderView',
            contentType: "application/json; charset=utf-8",
            success: this.onRenderSuccess,
            error: this.onError
        });
    },
    renderForm: function () {
        $.ajax({
            context: this,
            type: "POST",
            data: '{ "viewType": ' + this.viewType.CallbackForm + ' }',
            dataType: "json",
            url: this.serviceUrl + '/RenderView',
            contentType: "application/json; charset=utf-8",
            success: this.onRenderFormSuccess,
            error: this.onError
        });
    },
    removeScreen: function () {
        this.screen.animate({ 'opacity': 0 }, 500, function () { $(this).remove() });
    },
    onRenderSuccess: function (output) {
        _this = this;
        this.screen = $(output.d.HtmlContent);
        _gaq.push(['_trackPageview', '/vpv/ui/callback-popup/open/'], ['_trackEvent', 'UI', 'callback-popup', 'open']);
        this.trackingHolder.append('<iframe src="http://fls.doubleclick.net/activityi;src=1157406;type=augus877;cat=popup897;ord=1;num=1?" width="1" height="1" frameborder="0"></iframe>');

        $('body').append(this.screen);

        $('.closeBtn').click(function () {
            _this.removeScreen();
            _this.disablePopup();
        });
        $('.noThanks').click(function () {
            _this.removeScreen();
            _this.disablePopup();
            return false;
        });
        $('.callMe').click(function () {
            _this.removeScreen();
            _this.renderForm();
            return false;
        });
    },
    onRenderFormSuccess: function (output) {
        _this = this;
        this.screen = $(output.d.HtmlContent);
        $('body').append(this.screen);
        this.screen.css('opacity', 0).animate({ 'opacity': 1 }, 500);

        this.callbackForm = $('#pnlFormContainer');
        this.callbackForm.find('.closeBtn').click(function () {
            _this.removeScreen();
            _this.disablePopup();
        });

        this.callbackForm.find('#submit').click(function () {
            if (_this.validateForm()) {
                _this.saveForm();
            }

            return false;
        });
        $('html,body').animate({ scrollTop: 0 });
        _gaq.push(['_trackPageview', '/vpv/ui/callback-popup/call-me/'], ['_trackEvent', 'UI', 'callback-popup', 'call-me']);
        this.trackingHolder.find('iframe').remove();
        this.trackingHolder.append('<iframe src="http://fls.doubleclick.net/activityi;src=1157406;type=augus877;cat=popup013;ord=1;num=1?" width="1" height="1" frameborder="0"></iframe>');
    },
    onError: function (xmlRequest) {
        if (typeof (console) !== 'undefined' && console != null)
            console.log(xmlRequest.status + ' \n\r ' + xmlRequest.statusText + '\n\r' + xmlRequest.responseText);
    },
    validateForm: function () {
        var formValidator = $('#callback-form').validate({
            rules: {
                txtFirstname: "required",
                txtSurname: "required",
                txtTelephone: {
                    required: true,
                    minlength: 2
                },
                txtEmail: {
                    required: true,
                    email: true
                }
            }
        });

        var isValid = formValidator.form();

        var selectedTitle = $('#ddlTitle option:selected').val();
        var selectedPreference = $('#ddlContactPreference option:selected').val();
        var selectedInterests = $('#fldSelectedInterests').find("input:checked");

        if (selectedTitle == 'none')
            $('#ddlTitle').after('<label for="ddlTitle" generated="true" class="error">This field is required.</label>');
        if (selectedPreference == 'none')
            $('#ddlContactPreference').after('<label for="ddlContactPreference" generated="true" class="error">This field is required.</label>');
        if (selectedInterests.length == 0) {
            $('#checkInterestsError').css('display', 'block');
        }

        if (isValid)
            isValid = selectedPreference != 'none' && selectedTitle != 'none' && selectedInterests.length > 0;

        return isValid;
    },
    saveForm: function () {
        var selectedInterests = $('#fldSelectedInterests').find("input:checked");
        var selectedInterestValues = '';

        for (var i = 0; i < selectedInterests.length; i++) {
            if (selectedInterestValues.length > 0)
                selectedInterestValues += ', ';

            selectedInterestValues += $(selectedInterests[i]).val();
        }

        var referrer = document.location.href;
        if (location.href.indexOf("#") > -1)
            referrer = document.location.href.replace(/\/?#/, "/");

        var postObj = {
            "callbackData": {
                "ContactData": {
                    "Title": $('#ddlTitle option:selected').val(),
                    "Firstname": $('#txtFirstname').val(),
                    "Surname": $('#txtSurname').val(),
                    "Phone": $('#txtTelephone').val(),
                    "MobileNumber": $('#txtMobile').val(),
                    "ContactPreference": $('#ddlContactPreference option:selected').val(),
                    "Email": $('#txtEmail').val()
                },
                "HttpReferrer": referrer + '#callback-popup',
                "SelectedInterests": selectedInterestValues
            }
        };

        _gaq.push(['_trackPageview', 'Call back pop up / Request a call back - Confirmation'], ['_trackEvent', 'UI', 'callback-popup', 'Confirmation']);

        this.trackingHolder.find('iframe').remove();
        this.trackingHolder.append('<iframe src="http://fls.doubleclick.net/activityi;src=1157406;type=augus877;cat=popup067;ord=1;num=1?" width="1" height="1" frameborder="0"></iframe>');

        // Register gwo conversion
        gaConversion();

        $.ajax({
            context: this,
            type: "POST",
            data: JSON.stringify(postObj),
            dataType: "json",
            url: this.serviceUrl + '/SaveCallback',
            contentType: "application/json; charset=utf-8",
            success: this.onSaveSuccess,
            error: this.onError
        });
    },
    onSaveSuccess: function (output) {
        this.removeScreen();
        $.ajax({
            context: this,
            type: "POST",
            data: '{ "viewType": ' + this.viewType.CallbackComplete + ' }',
            dataType: "json",
            url: this.serviceUrl + '/RenderView',
            contentType: "application/json; charset=utf-8",
            success: this.onRenderComplete,
            error: this.onError
        });
    },
    onRenderComplete: function (output) {
        _this = this;
        this.screen = $(output.d.HtmlContent);
        $('body').append(this.screen)
        this.screen.css('opacity', 0).animate({ 'opacity': 1 }, 500);

        $('#callback-complete').find('.close, .closeBtn').click(function () {
            _this.removeScreen();
            _gaq.push(['_trackPageview', '/vpv/ui/callback-popup/close/'], ['_trackEvent', 'UI', 'callback-popup', 'close']);
        });
        $.cookie('state', 'completed', { expires: 30, path: '/' });
    },
    disablePopup: function () {
        $.ajax({
            context: this,
            type: "POST",
            data: '{ }',
            dataType: "json",
            url: this.serviceUrl + '/DisablePopup',
            contentType: "application/json; charset=utf-8",
            error: this.onError
        });
        _gaq.push(['_trackPageview', '/vpv/ui/callback-popup/close/'], ['_trackEvent', 'UI', 'callback-popup', 'close']);
    }
};

try {
    CallbackPopup.registerClass('CallbackPopup');
} catch (e) {
    if (typeof (console) !== 'undefined' && console != null)
        console.log(e);
}
Sys.Application.notifyScriptLoaded();

function gaConversion() {
    // GWO Tracking - Doors vs Transform AB test
    _gaq.push(['gwo._setAccount', 'UA-5372852-2']);
    _gaq.push(['gwo._setDomainName', 'everest.co.uk']);
    _gaq.push(['gwo._setAllowHash', false]);
    _gaq.push(['gwo._setAllowLinker', true]);
    _gaq.push(['gwo._trackPageview', '/3265878974/goal']);
    // End GWO Tracking - Doors vs Transform AB test
}

function gaConversionNewAppForm() {
    _gaq.push(['gwo._setAccount', 'UA-5372852-2']); 
    _gaq.push(['gwo._setDomainName', 'everest.co.uk']);
    _gaq.push(['gwo._setAllowHash', false]); 
    _gaq.push(['gwo._setAllowLinker', true]);
    _gaq.push(['gwo._trackPageview', '/2051681041/goal']);
}

$(document).ready(function() { 
    $('#social-icon-container a').click(function () {
        $.get('http://ad-emea.doubleclick.net/activity;src=3428238;type=socia344;cat='+ $(this).attr('rel') +';ord=1;num=' + ((Math.random() + '') * 10000000000000) + '?');
    });
});

