//var flashVersion = jQuery.fn.flash.hasFlash.playerVersion().split(",");
//var hasFlash = flashVersion[0] >= 7;

// scriptStrings object for any content that gets rendered via JavaScript
// error messages are defined in more depth in the errorStrings object
var fieldErrorMsg="";
var scriptStrings = {
    contactFormSuccess: "Thanks for taking the time to send us an email. We\'ll be in touch soon.",
    deviceSuccess: "Thank you for submitting your device!",
    enterTextHere: "Enter text here",
    enterCustomItem: "Enter a custom checklist item.",
    heartbeatFailed: "An error occurred submitting your data. Please try again.",
    modalFailed: "We're sorry - an error occurred when we tried to load that info. Please try again.",
    loadingMessage: "Loading...",
    newsletterEmailInvalid: "Invalid email format.",
	invalidcode: "Invalid code.",
    newsletterError: "Sorry, a error occurred.",
    newsletterSuccess: "Thanks for signing up!",
    pleaseTryAgain: "Please try again.",
    topErrorGeneric: "There are some errors on the form below.<br />Please update the indicated fields then try again.",
    topErrorMultipleBuy: "There are some errors on the form below.<br />Please update the indicated fields and click the Buy button.",
    topErrorMultipleNext: "There are some errors on the form below.<br />Please update the indicated fields click the Next button.",
    printFormatting: "<a href=\"#\" id=\"removePrintStyles\" class=\"backLink\">&laquo; Go back</a> We\'ve formatted the page for printing. <a id=\"printLink\"  href=\"javascript:window.print()\">Print</a>",
    promoError: "You have entered a promo code without clicking \"apply\".<br />Please click \"apply code\" or delete the promo code before continuing.",
    registrationFailed: "We are unable to register your account.  Please try again shortly or <a href=\"CHATURL\">Chat with Gogo Customer Care</a>."
};

// error message strings: defined as arrays, where [0] = the field level message and [1] = the top-of-page message
var errorStrings = {
    billingAddressRequired: ["Please enter an Address.", "Address 1 is required. Please update the indicated fields and click BUY."],
    cardNumberRequired: ["Please enter your Card Number.", "Card Number is required. Please update the indicated field and click BUY."],
    cardNumberSyntax: ["A Card Number must be 15 or 16 digits, numerals only.", "A Card Number must include 15 or 16 digits, numerals only."],
    cardTypeRequired: ["Please select a Card Type.", "Card Type is required. Please update the indicated field and click BUY."],
	characterRestrictionsName: ["Your entry cannot include these characters:<br />&amp; &lt; &gt; &quot;", "Name on card fields cannot accept the characters: &amp; &gt; &lt; &quot;"],
	characterRestrictionsAddress: ["Your entry cannot include the characters:<br />&amp; &lt; &gt; &quot; % | ^ \\ \/", "Address-related fields cannot accept the characters: &amp; &gt; &lt; &quot; % | ^ \\ \/"],
    characterRestrictionsAddress2: ["Your entry cannot include the characters:<br />&amp; &lt; &gt; &quot; % | ^ \\ \/", "Address-related fields cannot accept the characters: &amp; &gt; &lt; &quot; % | ^ \\ \/"],	
    characterRestrictionsGeneral: ["Your entry cannot include these characters:<br />&amp; &lt; &gt; &quot;", "Your entry cannot include these characters:<br />&amp; &gt; &lt; &quot;"],
    characterRestrictionsNonLatin: ["Your entry contains characters that we can\'t process. Please edit your entry and try again.", "Your entry contains characters that we can\'t process. Please edit your entry and try again."],
    characterRestrictionsUsername: ["The Username cannot contain spaces or the characters: ( ) , . ; : &gt; &lt; @ [ ] \/ \\ | _ % & ? \"", "The Username cannot contain certain special characters. Please try a simpler Username."],
	charactersTabsRestrictionsUsername: ["The Username cannot contain spaces, tabs or the characters: ( ) , . ; : &gt; &lt; @ [ ] \/ \\ | _ % & ? \"", "The Username cannot contain certain special characters. Please try a simpler Username."],
	charactersTabsRestrictionsContactUsername: ["The Username cannot contain spaces, tabs or the characters: ( ) , . ; : &gt; &lt; @ [ ] \/ \\ | _ % & \" ?", "The Username cannot contain certain special characters. Please try a simpler Username."],
    cityRequired: ["Please enter a City.", scriptStrings.topErrorMultipleBuy ],
    citySyntax: ["Please re-enter your City. Check your use of punctuation, special characters, and/or spaces.", scriptStrings.topErrorMultipleBuy ],
    contactRequired: ["Please provide at least one point of contact.", "Please provide at least one point of contact."],
    countryRequired: ["Please select a Country.", "Country is required. Please update the indicated fields and click BUY"],
    emailRequired: ["Please enter your Email Address.", "Email Address is required. Please update the indicated field and click Next.", "Please enter a valid Email Address."],
    emailInvalid: ["Please re-enter your Email Address. Check your use of punctuation, special characters, and/or spaces.", scriptStrings.topErrorMultipleNext],
    emailAlreadyUsed: ["Please enter a different Email Address.", "The Email Address you entered has already been used. Please update the indicated field and click Next."],
    emailConfirmRequired: ["Please re-enter your Email Address.", "Email confirmation is required. Please update the indicated field and click Next."],
    emailConfirmMismatch: ["Email Addresses do not match.", "Your Email Addresses do not match. Please update the indicated field and click Next."],
    expirationMonthAndYearRequired: ["Please select the Expiration Month and Year for this card.", "Card Expiration Month and Year are required. Please update the indicated fields and click BUY."],
    expirationMonthRequired: ["Please select the Expiration Month for this card.", "Card Expiration Month is required. Please update the indicated fields and click BUY."],
    expirationYearRequired: ["Please select the Expiration Year for this card.", "Card Expiration Year is required. Please update the indicated fields and click BUY."],
    firstNameRequired: ["Please enter your First Name.", "First Name is required. Please update the indicated field and click Next."],
    firstNameSyntax: ["Your entry cannot include the characters: & < > \" % | ^ \ /", scriptStrings.topErrorMultipleNext ],
    genericRequired: ["Required field.", scriptStrings.topErrorGeneric],
    lastNameRequired: ["Please enter your Last Name.", "Last Name is required. Please update the indicated field and click Next." ],
    lastNameSyntax: ["Your entry cannot include the characters: & < > \" % | ^ \ /", scriptStrings.topErrorMultipleNext ],
    checkSyntax: ["Your entry cannot include the characters: & < > \" % | ^ \ /", scriptStrings.topErrorMultipleNext ],
    nameRequired: ["Please enter your Name.", scriptStrings.topErrorGeneric],
    nameOnCardRequired: ["Name on card is required.", ""],
    passwordAlphanumeric: ["Password may contain letters and numbers only.", "Password may contain letters and numbers only."],
    passwordRequired: ["Please enter a Password.", "Password is required. Please update the indicated field and click Next."],
    passwordChars: ["Please re-enter a Password that is at least 6 characters.", "Password must be at least 6 characters. Please update the indicated field and click Next."],
    passwordWhitespace: ["Password cannot contain spaces or tabs.", "The Password cannot contain spaces or tabs. Please update the indicated field and click Next."],
    passwordConfirmMismatch: ["Passwords do not match.", "Your passwords do not match. Please update the indicated field and click Next."],
    passwordConfirmRequired: ["Please re-enter your Password.", "Password confirmation is required. Please update the indicated field and click Next."],
    passwordReminderRequired: ["Please choose a Reminder Question.", "A Password Reminder Question is required. Please update the indicated field and click Next."],
    passwordReminderAnswerRequired: ["Please enter a Reminder Answer.", "An answer to the Password Reminder Question is required. Please update the indicated field and click Next."],

    postalCodeRequired: ["Please enter a Zip/Postal Code.", "Zip/Postal code is required. Please update the indicated fields and click BUY."],
    postalCodeSyntax: ["Please re-enter your Zip/Postal Code. Check your use of punctuation, special characters, and/or spaces.", scriptStrings.topErrorMultipleBuy],
    phoneRequired: ["Please provide a Phone Number.", "Please provide a Phone Number."],
    phoneSyntax: ["Phone numbers cannot contain letters.", "Phone numbers cannot contain letters."],
    securityCodeRequired: ["Security Code is required.", "Security Code is required. Please update the indicated field and click BUY."],
    securityCodeSyntax: ["Security Code is 3 or 4 digits.", "Security Code is 3 or 4 digits."],
    stateRequired: ["Please select a State.", "State is required. Please update the indicated fields and click BUY."],
    termsRequired: ["Please accept the Terms of Use.", "Acceptance of Terms of use is required. Please update the indicated field and click Next."],
    usernameAlphanumeric: ["Username may contain letters and numbers only.", "Username may contain letters and numbers only."],
    usernameExists: ["Please enter a different Username.", "That Username is already taken. Please update the indicated field and click Next."],
    usernameRequired: ["Please enter a Username.", "Username is required. Please update the indicated field and click Next."],
    usernameSyntax: ["Please re-enter your username. Check your use of punctuation, special characters, and/or spaces.", scriptStrings.topErrorMultipleNext],
    usernameWhitespace: ["Username cannot contain spaces or tabs.", "The Username cannot contain spaces or tabs. Please update the indicated field and click Next."],
    usernameConfirmRequired: ["Please re-enter your Username.", "Username confirmation is required. Please update the indicated field and click Next."],
    usernameConfirmMismatch: ["Please re-enter your Username.", "Your Usernames do not match. Please update the indicated field and click Next."],
    usernameReminderRequired: ["Please choose a Reminder Question.", "A Username Reminder Question is required. Please update the indicated field and click Next."],
    usernameReminderAnswerRequired: ["Please enter a Reminder Answer.", "An answer to the Username Reminder Question is required. Please update the indicated field and click Next."],
    usZipFormat: ["US Zip code format: ##### or #####-####.", "US Zip code format is invalid. Please use ##### or #####-####."]
 };

// allows CSS-driven tooltips to also work with keyboard focus in IE6+7
function bindIEfocusHelpers()
{ 
    $('a.formHelp').focus(function()
    {
        $(this).addClass('focusedFormHelp');
    }).blur(function()
    {
        $(this).removeClass('focusedFormHelp');            
    });
}

// signout function
function signOut(logoutURL)
{
    var check=window.confirm("Are you sure you want to sign out?\nIf you have a session running, this will disable your internet connection.");
    if(check)
    {
        //dcsMultiTrack('DCS.dcsuri', '/abp/log_in/log_out_success.htm', 'WT.ti', 'Gogo Inflight Internet - Log out Success', 'WT.cg_n', 'Log_in', 'WT.cg_s', 'Log_out_success');
        window.parent.top.location.href = logoutURL;
   }
    else
    {
        return false;
    }
}

// participating airlines nav opacity treatment
function airlinesNavOpacity() {
    $("#airlinesNav img").not("#airlinesNav li.current img").css('opacity',0.85);
}

function validateEmailAlertsForm($form)
{
    $form.validate("", [
    {
		
        field: "#emailAddress",
        rules: {
            required: [ errorStrings.emailRequired[0], "" ],
            email: [ errorStrings.emailInvalid[0], "" ]
        }
    }
    ]); 
    return !$form.hasClass("hasError");
}

// modals
(function($)
{
    var isIE6 = $.browser.msie && $.browser.version == "6.0";
    
    var globals = 
        {
            text: "Processing, please wait",
            logo: "#logo",
            image: "img/animated_planes.gif",
            loadRequest: {},
            isVisible: false
        };
        
    $.fn.gogoModal = function(options)
        {
            if (this.length == 0) return this;
            var opts = $.extend({}, $.fn.gogoModal.defaults, options);
            if (isNaN(opts.timeout))
            {
                opts.timeout = $.fn.gogoModal.defaults.timeout;
            }
            init();
            return this.each(function()
                {
                    var $this = $(this);
                    if ($this.is("a"))
                    {
                        var urlToLoad = $this.attr('href');
                        $this.click(function() 
                            {
                                try
                                {
                                    $("#gogoModalBackground").css('opacity', 0).show().fadeTo(150, 0.65, function() {
                                        if(isIE6)
                                        {
                                            var scrollTop = $(document).scrollTop();
                                            var windowHeight = $(window).height();
                                            var topPos = $(document).scrollTop() + (windowHeight / 2) - 16;
                                            $('#gogoModalLoading').css('top', topPos);
                                        }
                                        $('#gogoModalLoading').show();
                                    });
                                    if (opts.iframe)
                                    {
                                        loadRequest = 'iframed';
                                        $('#modalContent').html('<iframe src="'+urlToLoad+'"id="modalIframe" scrolling="no" frameborder="0"></iframe>');
                                        showModal(opts.size);
                                    }
                                    else
                                    {
                                        loadRequest = $.ajax(
                                        {
                                            url: urlToLoad,
                                            cache: false,
                                            error: function() {
								                hideModal(false, opts.complete);
                                                alert(scriptStrings.modalFailed);
                                            },
                                            success: function(response){
                                                $("#modalContent").html(response);
                                                showModal(opts.size);
                                            }
                                        });
                                    }
                                }
                                catch (ex)
                                {
                                    hideModal(false, opts.complete);
                                    alert(scriptStrings.modalFailed);
                                }
                                return false;
                            });
                    }
                });
        };

    $.fn.gogoModal.defaults = 
        {
            validation: "",
            complete: "",
            size: "normal",
            iframe: false
        };

    $.gogoModal = {};
    $.gogoModal.setGlobals = function(options)
        {
            var opts = $.extend({}, globals, options);
            $.each(opts, function(key, value)
                {
                    if (globals[key])
                    {
                        globals[key] = value || globals[key];
                    }
                });
        };
        
    function init()
        {
            if ($("#gogoModalBackground").length == 0)
            {
                var html = '<div id="gogoModalBackground"></div><div id="gogoModalLoading"></div><div id="gogoModal"><div id="modalTopCap"></div><div id="modalContent"></div><div id="modalBottomCap"></div><a href="#" id="modalClose">Close</a></div>';
                $("body").append(html);
                $("#gogoModalBackground, #modalClose").click(function() { hideModal(); return false; });
                $(document).keydown(function (e) {
                    if($.gogoModal.isVisible)
                    {
                        if (e == null) { // ie
                            keycode = event.keyCode;
                        } else { // mozilla
                            keycode = e.which;
                        }
                        if(keycode == 27){ // esc key
							hideModal();
                        }
                    }
                });
                if (isIE6)
                {
                    $(window).scroll(redraw).resize(redraw);
                }
            }
        };

    function redraw(eventObject)
        {
            $("#gogoModalBackground").height($(document).height());
            var content = $("#gogoModal");
            var topPos = $(document).scrollTop() - ($("#gogoModal").height() / 2);
            content.stop().animate({ marginTop: topPos }, 250, "linear");
        };  
        
    function showModal(size) 
        {
            $.gogoModal.isVisible = true;
            var scrollTop = $(document).scrollTop();
            var modalHeight = $('#gogoModal').height();
            var windowHeight = $(window).height();
            if (size === 'small')
            {
                $("#gogoModal").addClass('smallModal');
            }
            if (isIE6)
            {
                $("select").hide();
                var topPos =  scrollTop - (modalHeight / 2);
            } 
            else
            {
                var topPos = -(modalHeight / 2);
            }
            //handle the edge case: modal height taller than viewport
            if ( modalHeight > windowHeight ) {
                var topPos = - ( windowHeight / 2) + scrollTop + 5;
                $('#gogoModal').css('position', 'absolute');
                if (isIE6)
                {
                    $(window).unbind('scroll', redraw).unbind('resize', redraw);
                }
            }
            $("#gogoModal").css('margin-top', topPos).slideDown(150, function() {
                if (isIE6)
                {
                    $("#gogoModalBackground").height($(document).height());
                }
                $('#gogoModalLoading').hide();
            });
            setTimeout(replaceModalHeader, 0);
        };
        
    function hideModal(success, complete)
        {

            if ($('#setupVideo').length > 0 && $('#setupVideo').css('display') != 'none')
            {
                $('#swfWrap')[0].stopVideo();
            }
            
            $.gogoModal.isVisible = false;
            if (typeof(loadRequest) == 'object')
            {
                loadRequest.abort();
            }
            $("#gogoModalBackground").fadeTo(50, 0.0, function() 
            {
                $(this).add('#gogoModalLoading').hide();
                $("#gogoModal").slideUp(100, function() 
                {
                    $(this).hide().removeClass('smallModal').attr('style', '');
                });
                if (isIE6)
                {
                    $("select").show();
                }                                
                if ($.isFunction(complete))
                {
                    complete(success);
                }
            });
            $('#modalIframe').remove();
            if (isIE6) {
                $(window).scroll(redraw).resize(redraw);
            }
            loadRequest = {};
        };
        
    function replaceModalHeader()
        {
            if(typeof sIFR == "function"){
                sIFR.replaceElement("#modalHeader", named({sFlashSrc: "/static/dotcom/js/GothamLight.swf", sTextAlign: "left", sColor: "#3C3C3C"}));
            };
        };
        
})(jQuery);

// Error plug-in
(function($)
{
    var id = "error";
    
    $.error = 
    {
        
        log: function(message)
            {
                if (message == undefined) return;
                var $this = $("#" + id);
                if ($this.length == 0)
                {
                    $("#primary h1:first").after("<div class=\"error\" id=\"" + id + "\"></div>");
                    $this = $("#" + id);
                }
                if ($this.length > 0)
                {
                    var alert = false;
                    if (arguments.length > 1)
                    {
                        if (arguments[1] === true)
                        {
                            alert = true;
                        }
                    }
                    if ($this.css("display") == "none")
                    {
                        if (alert)
                        {
                            $this.addClass("alert");
                        }
                        else
                        {
                            $this.removeClass("alert");
                        }
                        $this.html(message).fadeIn(250, function() 
                            {
                                var top = $this.offset().top;
                                if ($(document).scrollTop() > top)
                                {
                                    $("body,html").stop().animate({ scrollTop: top }, 250);
                                }
                            });
                    }
                    else
                    {
                        $this.stop().fadeOut(250, function() 
                            {
                                $.error.log(message, alert);
                            });
                    }
                }
            },
        
        clear: function()
            {
                $("#" + id).fadeOut(250, function() 
                    {
                        $(this).html("");
                    });
            }
    };
    
})(jQuery);

// Form validation plug-in
(function($)
{
        
    $.fn.validate = function(genericError, fields)
        {
            if (this.length == 0) return this;
            if (genericError == undefined)
            {
                genericError = "";
            }
            fields = fields ? $.makeArray(fields) : [];
            $.each(fields, function(field, value) 
                {
                    fields[field] = $.extend({}, $.fn.validate.field, value);
                    fields[field].$field = $(fields[field].field);
                    fields[field].rules = $.extend({}, fields[field].rules);
                    $.each(fields[field].rules, function(rule, value) 
                        {
                            try
                            {
                                if (typeof(value) == "string")
                                {
                                    value = { message: value, formMessage: value };
                                }
                                else if (value.constructor.toString().indexOf('Array') > -1 && value.length == 2)
                                {
                                    value = { message: value[0], formMessage: value[1] };
                                }
                                fields[field].rules[rule] = $.extend({}, $.fn.validate.field.rules, value);
                            }
                            catch (ex)
                            {
                            }
                        });
                    if (fields[field].rules.required) 
                    {
                        var value = fields[field].rules.required;
                        delete fields[field].rules.required;
                        fields[field].rules = $.extend({ required: value }, fields[field].rules);
                    }
                });
            var completeCallback = arguments.length > 2 ? arguments[2] : "";
            return this.each(function()
                {
                    var $this = $(this);
                    if ($this.is("form"))
                    {
                        $.validate.clear($this);
                        var failed = [];
                        var errorMessage = genericError;
                        $.each(fields, function(index, value) 
                            {
                                if (this.$field.length == 1) 
                                {
                                    var $field = this.$field;
                                    $.each(this.rules, function(key, rule) 
                                        {
                                            if (!$.isFunction(key)) {
                                                key = eval(key);
                                            }
                                            if ($.isFunction(key)) {
                                                var params = $.makeArray(rule.params);
                                                params.unshift($field);
                                                if (!key.apply(this, params)) {
                                                    $.validate.showError($field, rule.message);
                                                    failed.push(value.field);
                                                    errorMessage = failed.length == 1 ? rule.formMessage : genericError;
                                                    return false;
                                                }
                                            }
                                        });
                                }
                            });
                        if (failed.length > 0)
                        {
							webtrendsClientSideValidationsError(fieldErrorMsg);
							fieldErrorMsg="";
                            $this.addClass("hasError");
                            if (errorMessage != "")
                            {
                                $.error.log(errorMessage, true);
                            }
                            if ($.isFunction(completeCallback))
                            {
                                completeCallback.call(document, failed);
                            }
                        }
                    }
                });
        };
    
    $.fn.validate.field = 
        {
            field: "",
            rules: {}
        };
    $.fn.validate.field.rule = 
        {
            message: "",
            formMessage: "",
            params: []
        };
    
    $.validate = {
        clear: function($form)
            {
                $form.removeClass("hasError");
                $form.find("div.error, div#error").remove();
                $form.find(":input.error").removeClass("error");
            },
            
        showError: function($target, message)
            {
                var prependSelf = arguments.length == 3 && arguments[2] == true;
				if(message !="") {
					fieldErrorMsg=fieldErrorMsg+message+';';
				}
                if (prependSelf) 
                {
                    writeError($target, message);
                } 
                else 
                {
                    writeError($target.closest("div"), message);
                    $target.addClass("error");
                }
            },
        
        validateWith: function($field, validator)
            {
                validator = eval(validator);
                if ($.isFunction(validator)) {
                    var params = [];
                    if (arguments.length > 2) {
                        for (var i = 2; i < arguments.length; i++) {
                            params.push(arguments[i]);
                        }
                    }
                    params.unshift($field);
                    return validator.apply(this, params);
                }                
                return false;
            }
            
    };

    function writeError($target, message) 
    {
        if (message && message != "")
        {
            $target.prepend("<div class=\"error\">" + message +"</div>");
        }
    };
        
    function value($field) 
    {
        return $.trim($field.val());
    };
                
    function required($field)
    {
        if ($field.is(":radio, :checkbox")) 
        {
            return $field.is(":checked");
        }
        return value($field) != "";
    };
    
    function passwordRequired($field)
    {
	    if(/\s/.test($field.val())){
		   return true;
	    }
	    else{			 
        return value($field) != "";        
    }    
    };
    function characterRestrictionsGeneral($field)
    {
        return /^[^&<>"]+$/i.test(value($field));  
    };

    function characterRestrictionsAddress($field)
    {
        return /^[^&<>"%\|\^\\\/]+$/i.test(value($field));  
    };
	
	function characterRestrictionsName($field)
    {
        return /^[^&<>"]+$/i.test(value($field));  
    };
    
    
    function characterRestrictionsAddress2($field)
    {
	   if($('#billingAddress2').val() != '')
	{
	   return /^[^&<>"%\|\^\\\/]+$/i.test(value($field));  
	}
	 else
        {
            return true;
        }
    };
        
    function characterRestrictionsNonLatin($field)
    {
        var val = value($field);
        var len = val.length;
        for (var i = 0; i < len; i++)
        {
            if (val.charCodeAt(i) > 255 || val.charCodeAt(i) < 32)
            {
                return false;
            }   
        }
        return true;
    };

    function characterRestrictionsUsername($field)
    {
        return /^[^\s\(\)\[\]\.\\\|,;:><"\/?@_%&]+$/i.test(value($field));  
    };

    function alphanumeric($field)
    {
        return /^[a-z0-9]+$/i.test(value($field));  
    };
            
    function email($field)
    {
        return /^[a-z0-9\'+_-]+(?:\.[a-z0-9\'+_-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(value($field));
    };
        
    function confirm($field, selector)
    {
        return value($field) == value($(selector));
    };
    
    function minLength($field, minLength)
    { 
        return value($field).toString().length >= minLength;
    };
        
    function maxLength($field, maxLength)
    {
        var truncate = arguments.length == 3 && arguments[2] == true;
        var val = value($field).toString();
        var valid = val.length <= maxLength;
        if (!valid && truncate)
        {
            $field.val(val.substr(0, maxLength));
            return true;
        }
        return valid;
    };
    
    function noWhitespace($field)
    {
        return !(/\s/.test($field.val()));
    };
    
    function usZip($field)
    {
        if($('#country').val() === 'US')
        {
            return /^\d{5}([\-]\d{4})?$/.test(value($field));
        }
        else
        {
            return true;
        }
    };
    
    function creditCardNumber($field)
    {
        return /^[0-9]{15,16}$/.test(value($field));   
    };
    
    function securityCode($field)
    {
        return /^[0-9]{3,4}$/.test(value($field));
    };
	
	function firstname($field)
    {
        return /^[^&<>"%\|\^\\\/]+$/i.test(value($field));
    };
    
    function lastname($field)
    {
        return /^[^&<>"%\|\^\\\/]+$/i.test(value($field));
    };
    function syntax($field)
    {
        return /^[^&<>"%\|\^\\\/]+$/i.test(value($field));
    };  
	
	function phoneNumber($field)
    {
        return /^[^A-Z]+$/i.test(value($field));
    }
    
})(jQuery);

// side tabs plug-in
(function($)
{       
    $.fn.gogoSideTabs = function()
    {
        $this = $(this);
        $this.children('div').not('div:first').hide();
        $($('.tertiaryNav li')[0]).addClass('current');
        $('.tertiaryNav a').click(function()
        {
            $('.tertiaryNav li').removeClass('current');
            $(this).parent('li').addClass('current');
            var targetContent = $(this).attr('href');
            $this.children('div').hide();                  
            if($(this).attr('id') === 'viewAll')
            {
                $this.children('div').fadeIn('fast');
            }
            else
            {
                $(targetContent).fadeIn('fast');
            }
            return false;
        });
    };
})(jQuery);

// headers+expanders plugin
(function($)
{       
    $.fn.gogoExpanders = function(options)
    {
        settings = jQuery.extend({
            trigger: ".expandTrigger",
            target: ".expandTarget",
            expandFirstItem: true,
            speed: 250
        }, options);
        $this = $(this);
        $(settings.target, ($this)).hide();
        $(settings.trigger).addClass('expander').toggle(
            function()
            {
                $(this).addClass('expanded').next(settings.target).slideDown(settings.speed, function()
                {
                    $(this).addClass('expanded');
                });
            },
            function()
            {
                $(this).removeClass('expanded').next(settings.target).removeClass('expanded').slideUp(settings.speed);
            }
        );
        if (settings.expandFirstItem)
        {
            $(settings.trigger + ':first').click();
        }
    };
})(jQuery);


// textarea character counter
function remainingCharacters(limit, textareaID, counterID)
{
    var text = $('#' + textareaID).val();
    var characters = text.length;
    var remaining = limit - characters;
    if (characters >= limit)
    {
        $('#' + textareaID).val(text.substr(0,limit));
        $('#' + counterID).html('0');
        return false;
    }
    else
    {
        $('#' + counterID).html(remaining);
        return true;
    }
}

// simple textarea limiter (no counter)
function limitCharacters(limit, textarea)
{
    var text = textarea.val();
    var characters = text.length;
    var remaining = limit - characters;
    if (characters >= limit)
    {
        textarea.val(text.substr(0,limit));
        return false;
    }
    else
    {
        return true;
    }
}

// basic email checker
function checkEmailFormat(email)
{
        return /^[a-z0-9'+_-]+(?:\.[a-z0-9'+_-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(email);
}

function webtrends(dcsURI,quest,topic,szTi)
{
	var question=  quest.replace( /^\s*/, "" ).replace( /\s*$/, "" );
	replaceValue("WT.ti",szTi)
	if(szTi=="ABP-LiveChat")
	{
		replaceValue("WT.cg_n","Customer Care");
		replaceValue("WT.cg_s","Live Chat");
	}
	if(szTi=="ABP-Search")
	{ 
		replaceValue("WT.cg_n","Miscellaneous");
		replaceValue("WT.cg_s","Search");
	}
	else if(szTi=="ABP-Search")
	{
		replaceValue("DCS.dcsuri",dcsURI);
		var WTossVal=$("#googleSearchBoxVal").val(); 
		keyValueString=keyValueString+",'WT.z_faq_topic'"+",'"+topic+"','WT.z_faq','"+question+"','WT.ti'"+",'"+szTi+"','WT.oss'"+",'"+WTossVal+"'";;
	}
	if (dcsURI==null || dcsURI.length==0)
	{
		keyValueString=keyValueString+",'WT.z_faq_topic'"+",'"+topic+"','WT.z_faq','"+question+"'";
		eval('dcsMultiTrack('+keyValueString+')');		
	}else
	{		

		if(szTi=="ABP-LiveChat")
		{
			replaceValue("DCS.dcsuri",dcsURI);
			keyValueString=keyValueString+",'WT.z_faq_topic'"+",'"+topic+"','WT.z_faq','"+question+"','WT.ti'"+",'"+szTi+"'";;
		}
		else if(szTi=="ABP-Search")
		{
			replaceValue("DCS.dcsuri",dcsURI);
			var WTossVal=$("#googleSearchBoxVal").val();
			keyValueString=keyValueString+",'WT.z_faq_topic'"+",'"+topic+"','WT.z_faq','"+question+"','WT.ti'"+",'"+szTi+"','WT.oss'"+",'"+WTossVal+"'";;
		}
		else
		{
			keyValueString="'DCS.dcsuri','"+dcsURI+"','WT.z_faq_topic'"+",'"+topic+"','WT.z_faq','"+question+"','WT.ti'"+",'"+szTi+"'";;
		}      
		eval('dcsMultiTrack('+keyValueString+')');   
	}


} 

function webtrendsCreateAccount(szTi,dcsURI,cgs,ti,zerror)
{
	if(szTi=="register2")
	{
		replaceValue("WT.ti","Dotcom ? SignUp Payment");
		replaceValue("DCS.dcsuri","/com/create_account/sign_up/add_credit_card.htm");
		replaceValue("WT.cg_s","Payment");
		keyValueString="'WT.z_error','"+zerror+"','DCS.dcsuri','"+dcsURI+"','WT.cg_s'"+",'"+cgs+"','WT.ti'"+",'"+ti+"'";;
		eval('dcsMultiTrack('+keyValueString+')');   
	}
}

function webtrendsPayment(szTi,desc,dcsURI,cgs,ti,zerror)
{
	if(szTi=="payment2")
	{
		replaceValue("WT.ti","Dotcom - Payment");
		replaceValue("DCS.dcsuri","/com/payment.htm");
		replaceValue("WT.cg_s","Error");
		replaceValue("Description","Payment");
		keyValueString="'WT.z_error','"+zerror+"','Description','"+desc+"','DCS.dcsuri','"+dcsURI+"','WT.cg_s'"+",'"+cgs+"','WT.ti'"+",'"+ti+"'";;
		eval('dcsMultiTrack('+keyValueString+')');   
	}
}

function webtrendsMarquee(index)
{
		if(index == 1) {
		dcsURI = "/com/gogo/promotions.htm";
		} else if(index == 2){
		dcsURI = "/com/gogo/promotions.htm";
		}		
		var keyValStr="'WT.z_error','Marquee_z_error','DCS.dcsuri','"+dcsURI+"','WT.cg_s'"+",'Marquee_cg_s','WT.ti'"+",'Marquee_ti'";;
		eval('dcsMultiTrack('+keyValStr+')');   
	
}

function webtrendsVCDownload()
{	
		dcsURI = "/com/gogo/VideoClientInstall.htm";		
		var keyValStr="'DCS.dcsuri','"+dcsURI+"','WT.cg_s'"+",'Dotcom_Video_LandingPage','WT.ti'"+",'Video'";;
		eval('dcsMultiTrack('+keyValStr+')');   
	
}

/**
				 * Executes the webtrends event call when the client side validation error occurs
				**/
				function webtrendsClientSideValidationsError(errorMsg){
					errorMsg=errorMsg.substring(0, errorMsg.length-1)
					keyValueString=keyValueString+",'WT.z_error'"+",'"+errorMsg+"'";
					eval('dcsMultiTrack('+keyValueString+')'); 
					errorMsg='';
					}

function replaceValue(key,value)
{
	
	var pos1=keyValueString.indexOf(key);
	
	var strtemp1=keyValueString.substring(0,pos1+(key.length+3));
	
	var strtemp2=keyValueString.substring(pos1+(key.length+3),keyValueString.length);
	
	strtemp2=strtemp2.substring(strtemp2.indexOf("'"),strtemp2.length);
	
	keyValueString=strtemp1+value+strtemp2;
	

}


// modals' sIFR + binding close commands
function bindIFramedModalBehaviors()
{
    if(typeof sIFR == "function")
    {
        sIFR.replaceElement("#modalHeader", named({sFlashSrc: "/static/dotcom/js/GothamLight.swf", sTextAlign: "left", sColor: "#3C3C3C"}));
    };

    $(document).keydown(function (e)
    {
        if (e == null) { // ie
            keycode = event.keyCode;
        } else { // mozilla
            keycode = e.which;
        }
        if(keycode == 27){ // 
            var p = window.parent;
            p.$('#modalClose').click();
        }
    });
}

// AddThis plugin variables & behavior setup
var addthis_hover_delay = 100;
var addthis_offset_top = -2;
var addthis_offset_left = -75;
var addthis_header_color = "#ffffff";
var addthis_header_background = "#289728";
//var addthis_brand = "Gogo";
var addthis_pub="gogoinflightdotcom";
var addthis_options = 'email, favorites, delicious, digg, facebook, google, linkedin, stumbleupon, technorati, twitter, yahoobkm, more';
//var addthis_script = '<script type="text/javascript" src="http://s7.addthis.com/js/200/addthis_widget.js"></script>';

// begin dom-ready behavior binding
// (for sitewide behaviors only -- page specific behaviors go in block near the bottom of each page)
$(document).ready(function(){  

	$(".toggle_container").hide();

	$("h2.trigger").click(function(){
		$(this).toggleClass("active").next().slideToggle("medium");
	});
	$("h2.triggerM").click(function(){
		$(this).toggleClass("active").next().slideToggle("medium");
	});

	$('#splashPricing_btn').click(function()
{
		dcsURI = "/com/gogo/splashPricing.htm";		
		var keyValStr="'DCS.dcsuri','"+dcsURI+"','WT.cg_s'"+",'Dotcom_Splash_Pricing','WT.ti'"+",'Pricing'";;
		eval('dcsMultiTrack('+keyValStr+')');  
});


$('#advertise_btn').click(function()
{
	var usrName =  $.trim($('#usrName').val());	 		 
	if(usrName == null || usrName.length ==0){
			$('#usrNameErrorDiv').addClass('error').show();
			return false;
		}
	if (!checkEmailFormat($('#emailAddress').val()))
        {
            $('#emailErrorDiv').addClass('error').show();
            return false;
        }
	 
	$('#frmAdvertise').submit();	
	 return true;
});

$('#returningRadio').click(function()
{
	$('#returningRadio').attr("name","_eventId_next");
	$('#signInSignUp').submit();
});

// Start Added for enterprise Portal AJAX
$('#singup_btn').click(function()
    {
        $('#frm_ipass').submit();
        return false;
    });
 

   $("#frm_ipass").bind("submit", function(e)
    {
         var $form = $(this);
		 var compCode =  $.trim($('#companyCode').val());
	 		 
		if(compCode == null || compCode.length ==0){
			alert("Please Enter Company Code.");			
			return false;
		}else{
				$('#companyCode').removeClass('error');
				e.preventDefault();
        
			    $.ajax(
		            {
		                type: "POST",
						url: '/gogo/enterpriseLanding.do',
		                timeout: '15000',
		                cache: false,
						dataType: 'html',
		                data: 'companyCode=' + compCode,
                error: function (XMLHttpRequest, textStatus, errorThrown)
                    {   
						alert ("Could not validate the Company Code due to technical difficulties. Please Try Again.");
                    },
                success: function (data, textStatus) 
                    {
												
						if(data=='200')
						{							
							//dcsMultiTrack('DCS.dcsuri', '/com/enterprise_landing_homepage.htm', 'WT.cg_n', 'Enterprise Landing', 'WT.cg_s', 'Enterprise_Landing', 'WT.rv', '0', 'WT.seg_1', 'Landing', 'WT.ti', 'Gogo Inflight Internet - Enterprise Landing Success');
							document.frm_ipass.submit();
                      
					 	}
						else if(data=='400')
						{
							alert("Invalid Company Code Entered.Please Try Again.");
							$('#companyCode').val('');
							//dcsMultiTrack('DCS.dcsuri', '/enterprise/homepage.htm', 'WT.cg_n', 'Miscellaneous', 'WT.cg_s', 'Enterprise_Landing', 'WT.rv', '0', 'WT.seg_1', 'Landing', 'WT.z_error', 'Invalid Company Code', 'WT.ti', 'Gogo Inflight Internet - Enterprise Landing Failure');
							return false;
						}
                     
                    }
		            });
	    
        }
    });
	
// END Added for enterprise Portal AJAX

// Added Script flash and toggle coverage

                $('#coverageDisclaimer').hide();
                $('#disclaimerToggle').show().toggle(function()
                {
                    $('#coverageDisclaimer').slideDown(250);
                    return false;    
                },
                function() {
                    $('#coverageDisclaimer').slideUp(100);
                    return false;    
                });
                
                var flashvars = {
                    flv: '/static/dotcom/flv/howGogoWorks.flv',
                    autoplay: true
                };
                var params = {
                    menu: false
                };
                var attributes = {};                
                swfobject.embedSWF("/static/dotcom/swf/GogoVideoPlayer.swf", "swfWrap", "368", "240", "9.0.0","", flashvars, params, attributes);
// ENDAdded Script flash and toggle coverage



    //$('body').append(addthis_script);
    var addthis_hover_delay = 100;
    $('#addThisPlugin').show();
    $('#addThisLink')
        .mouseenter(function()
        {
            return addthis_open(this, '', '[URL]', '[TITLE]');
        }).mouseleave(function()
        {
            addthis_close();
        }).click(function()
        {
            return addthis_sendto();
        });    
    
    // testimonial rotation
    // AIRCELL DEV: this is demo code and would best be replaced with server-side randomization   
   /* $('img.testimonialDisc').each(function()
    {
        var prefix ="img/testimonials/testimonial_";
        var num = Math.floor(Math.random()*12+1);
        var leadingZero = "";
        if (num < 10)
        {
            leadingZero = "0";
        }
        var suffix =".png";
        var newSrc = prefix + leadingZero + num + suffix;
        $(this).attr('src', newSrc);    
    });*/

    // replace H1s with brand font
    if(typeof sIFR == "function")
    {
        sIFR.replaceElement("h1", named({sFlashSrc: "/static/dotcom/js/GothamLight.swf", sWmode: "transparent", sTextAlign: "left", sColor: "#3C3C3C"}));
    };
    
    // navigation
    $('#nav').addClass('js');
    
    $('#nav>li.current').attr('currentNav', 'true').addClass('showSubnav'); 
    
    $('#nav>li').mouseover( function()
    {
        $(this).siblings().removeClass('showSubnav');
        $(this).addClass('showSubnav'); 
    });
    
    $('#nav>li').mouseout(function()
    {
        $(this).removeClass('showSubnav');
        $('#nav li[currentNav]').addClass('showSubnav');
    });
    
    $('#nav>li>a').click(function()
    {
        return false;
    }).focus(function()
    { 
        $(this).parent().siblings().mouseout();
        $(this).parent().mouseover();
    });
    
    $('#pageUtil a:first, #brand a:last').focus(function()
    {
        $('#nav>li').mouseout();
    });


    // bind signout modal
    $('#signOut').gogoModal({size: 'small'});
//	$('#returnSiginSignup').gogoModal({size: 'small', iframe: true});

    // bind chat popup launcher to all chat links    
    $('a#chatLink, a.chatLink').bind('click', function()
    {
        var dest = $(this).attr('href');
        var posX = ($(window).width() / 2) - 300;
        var posY = ($(window).height() / 2)  - 250;
        var features = "width=620,height=600,top="+posY+",left="+posX+",toolbar=no,menubar=no,scrollbars=yes,resizable=no";
        window.open(dest, 'chatWindow', features); 
        return false;
    });
    
    // reveal feedback link since JS is available, bind survey launcher
    $('a#feedback').show().click(function()
    {
		//O_LC(); return false;
		var dest = $(this).attr('href');
        var posX = ($(window).width() / 2) - 300;
        var posY = ($(window).height() / 2)  - 250;
        var features = "width=570,height=700,top="+posY+",left="+posX+",toolbar=no,menubar=no,scrollbars=yes,resizable=no";
        window.open(dest, 'feedbackWindow', features); 
        return false;
    });
	

    
    // focus the first field a form if it's in #primary
    //if ($('#primary form').length > 0)
    //{
    //    $('#primary form :input')[0].focus();
    //}
    

    // set up clear-on-focus for fields w/ pre-shown value
    $(".focusClear").bind("focus", function()
    {
        if (!$(this).attr("initval"))
        {
            var initVal = $(this).val();
            $(this).attr("initval",initVal);
        }
        if ($(this).val() == $(this).attr("initval"))
        {
            $(this).val("");
        }
    }).bind("blur", function()
    {
        if ($(this).val().match(/^\s*$/))
        {
            var initVal = $(this).attr("initval");
            $(this).val(initVal);
        }
    });

    // newsletter form
    $('#nlSubmit').click(function()
    {
        $('#newsletterSignup').submit();
        return false;
    });
    
    $('#nlMessaging').click(function()
    {
        $(this).hide().empty();
        $('#nlEmail')[0].focus();
    });

    $('#nlEmail').keydown(function()
    {
        if ($('#nlMessaging:visible')) {
            $('#nlMessaging').hide().empty();
        }
    });

    // field validation, newsletter signup form 
    $("#newsletterSignup").bind("submit", function(e)
    {
        var $form = $(this);
        var email = $('#nlEmail').val();
        $('#nlEmail').val('');
        if (!checkEmailFormat(email))
        {
            $('#nlMessaging').html(scriptStrings.newsletterEmailInvalid).addClass('error').show();
            $('#nlEmail').addClass('error');
            return false;
        }
        else
        {
            $('#nlEmail').removeClass('error');
            e.preventDefault();
            $.ajax(
            {
                type: "POST",
                url: '/gogo/newsletterSignup.do', // REPLACE WITH REAL URL OF NEWSLETTER SIGN-UP SCRIPT AJAX HANDLER
                timeout: '5000',
                cache: false,
                data: 'nlEmail=' + email,
                error: function (XMLHttpRequest, textStatus, errorThrown)
                {
                    $('#nlMessaging').html(scriptStrings.newsletterError).addClass('error').show();
                    function updateNewsletterError() { $('#nlMessaging').html(scriptStrings.pleaseTryAgain); }
                    setTimeout(updateNewsletterError, 1500);
                    $('body').append('text status: '+ textStatus + ', error thrown: ' + errorThrown);
                },
                success: function (data, textStatus) 
                {
                    $('#nlMessaging').empty().html(scriptStrings.newsletterSuccess).addClass('success').removeClass('error').show();
                    function theFade() { $('#nlMessaging').fadeOut('fast', function() { $(this).empty(); }); }
                    setTimeout(theFade,3000);
                }
            });
        }
    });
   // load sign in page asynchronously into modal    
    $('#signIn,#fgtUserNm,#siteMapSignIn,#returnSiginSignup').gogoModal({ size: 'small', iframe: true });
	
	if ((typeof(enterpriseConf) != 'undefined' ) && enterpriseConf!='')
	{
		$("#dotcomConfirmation").css('display', 'none');
		$("#enterpriseConfirmation").css('display', 'block');
	}
	
});//end dom-ready behavior binding