/*	******************************
PLUGIN - Protect Animation
Author: Jack Lukic - KNI
Notes: Prevents stuck animations with stop
******************************	*/
jQuery.fn.extend({
    protectAnimation: function() {
        $(this).each(function() {
            // stop current animation
            if ($(this).filter(':animated').size() > 0) {
                $(this).stop();
            }
            // prevent stuck style tag
            $(this).attr('style', '');
        });
        return this;
    }
});

/*	******************************
PLUGIN - 
Validate Form
		
Author: Jack Lukic - KNI
Last revision: April 2010
******************************	*/

jQuery.fn.extend({
    validateForm: function(fields, params) {
        // extensible
        var settings = {
            animateSpeed: 150,
            inlinePrompt: true,
            promptClass: 'prompt',
            onValid: function($field) {
                $field.removeClass('warn');
            },
            onInvalid: function($field) {
                $field.addClass('warn');
            },
            onSuccess: function() {
                return true;
            },
            onFailure: function() {
                return false;
            },
            validate: {
                empty: function(value) {
                    return !(typeof (value) == 'undefined' || '' == value);
                },
                either: function(value, alternateField) {
                    var either = false;
                    var altertanteValue = $('#' + alternateField).val();
                    if (!(typeof (altertanteValue) == 'undefined' || '' == altertanteValue)) either = true;
                    if (!(typeof (value) == 'undefined' || '' == value)) either = true;
                    return either;
                },
                email: function(value) {
                    return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(value);
                },
                match: function(value, matchingField) {
                    var matchingValue = $('#' + matchingField).val();
                    return (value.toString() == matchingValue.toString());
                },
                not: function(value, notValue) {
                    return (value != notValue);
                },
                url: function(value) {
                    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
                    return regexp.test(value);
                },
                zipcode: function(value) {
                    var regexp = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
                    return regexp.test(value);
                },
                //Zip or city and state required
                cszip: function(zVal, fields) {
                    var zregex = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
                    var flds = fields.split(', ');
                    var cVal = $('#' + flds[0]).val();
                    var sVal = $('#' + flds[1]).val();

                    if (!zregex.test(zVal)) {
                        if ((cVal == '') || (sVal == ''))
                            return false;
                        else
                            return true;
                    }
                    else
                        return true;
                }
            }
        };
        jQuery.extend(settings, params);
        // reduce object depth to validation (performance)
        var validate = settings.validate;
        // init blank errors object
        // iterate over all forms
        $(this).each(function() {
            // attach event handler
            //$(this).submit(function () {
            // start off with a clean record
            var errors = [];
            var allValid = true;
            jQuery.each(fields, function(fieldName, field) {
                // cache jq
                var $field = $('#' + fieldName);
                var fieldValid = true;
                // iterate over all validation types for a certain field
                jQuery.each(field, function(i, validation) {
                    var $promptField = $field.next('.' + settings.promptClass);
                    var promptExists = ($promptField.size() != 0);
                    // vars				
                    var type = validation.type;
                    var value = $field.val();
                    // pull out bracketed data
                    var bracketRegExp = /\[(.*?)\]/i;
                    var bracket = bracketRegExp.exec(type);
                    // if bracket notation is used, pass in extra parameters
                    if (typeof (bracket) != 'undefined' && bracket != null) {
                        var ancillary = bracket[1];
                        var functionType = type.replace(bracket[0], '');
                        var isValid = validate[functionType](value, ancillary);
                    }
                    else {
                        // call validate function specified to determine validness
                        var isValid = validate[type](value);
                    }
                    if (!isValid) {
                        if (settings.inlinePrompt) {
                            // create message container on first invalid validation attempt	
                            if (!promptExists) {
                                var $promptField = $('<div />')
										.addClass(settings.promptClass)
										.insertAfter($field)
									;
                            }
                            // add prompt message
                            $promptField
									.html(validation.prompt)
									.fadeIn(settings.animateSpeed)
								;
                        }
                        // Add error
                        errors.push(validation.prompt);
                        // form invalid
                        fieldValid = false;
                        allValid = false;
                        // break each loop for this field
                        return false;
                    }
                    else {
                        // hide prompt
                        if (settings.inlinePrompt) {
                            $promptField.hide();
                        }
                    }
                });
                // Field callback
                if (fieldValid) {
                    settings.onValid($field);
                }
                else {
                    settings.onInvalid($field);
                }
            });
            // Evaluate form callbacks
            if (allValid) {
                //return
                settings.onSuccess();
            }
            else {
                //return
                settings.onFailure(errors);
            }
            //});
        });
        return this;
    }
});

/*	******************************
PLUGIN - 
Input text prompt underlay
		
Author: Jack Lukic - KNI
Last revision: April 2010
******************************	*/

jQuery.fn.extend({
    inputPrompt: function(text, params) {
        // extensible
        var settings = {};
        jQuery.extend(settings, params);
        // iterate
        $(this).each(function() {
            // cache
            var $field = $(this);
            var $label = $field.prev('label');
            // init
            var hasUserText = true;
            if ($(this).val() == '') {
                $label.html(text);
                var hasUserText = false;
            }
            // events
            $field.keypress(function() {
                $label.html(' ');
            });
            $field.focus(function() {
                $label.addClass('focus');
                $field.addClass('focus');
                $label.html(' ');
            });
            $(this).blur(function() {
                $label.removeClass('focus');
                $field.removeClass('focus');

                if ($(this).val() == '')
                    $label.html(text);
                else
                    $label.html(' ');
            });
            $label.click(function() { $field.focus(); });
        });
        return this;
    }
});

var config = {
    contactUs: {
        url: 'Handlers/ContactUsHandler.aspx',
        messages: {
            submit: "Submitting form",
            error: "There was a server error processing your request"
        },
        form: {
            defaultText: {
                comments: 'Type Your Comments',
                location: "Where did you visit Phillips 66",
                dateDay: new Date().getDate(),
                dateMonth: new Date().getMonth() + 1,
                dateYear: new Date().getFullYear(),
                firstName: 'Your first name',
                lastName: 'Your last name',
                address1: 'Address',
                address2: 'Apt #',
                city: 'City name',
                zipcode: 'xxxxx',
                phoneArea: 'xxx',
                phonePrefix: 'xxx',
                phoneSuffix: 'xxxx',
                email: 'yourname@email.com',
                emailConfirm: 'yourname@email.com'
            },
            validation: {
                subject: [{
                    type: 'empty',
                    prompt: 'Please select a topic'
}],
                    comments: [{
                        type: 'empty',
                        prompt: 'Don\'t forget to leave a comment'
}],
                        firstName: [{
                            type: 'empty',
                            prompt: 'Please enter your first name.'
}],
                            lastName: [{
                                type: 'empty',
                                prompt: 'Please enter your last name.'
}],
                                state: [{
                                    type: 'empty',
                                    prompt: 'Please select your state'
}],
                                    email: [
					{
					    type: 'empty',
					    prompt: 'Please enter your email address'
					},
					{
					    type: 'email',
					    prompt: 'Please enter a valid email address'
					},
					{
					    type: 'match[emailConfirm]',
					    prompt: 'Please verify your email entries matches'
					}
				],
                                    emailConfirm: [
					{
					    type: 'empty',
					    prompt: 'Please re-enter your email address'

					},
					{
					    type: 'email',
					    prompt: 'Please enter a valid email address'
					},
					{
					    type: 'match[email]',
					    prompt: 'Please verify your email entries matches'
					}
				]
                                }
                            }
                        },
                        register: {
                            url: 'Handlers/RegistrationHandler.aspx',
                            messages: {
                                error: "There was a server error processing your request"
                            },
                            height: {
                                normal: '293px',
                                thankYou: '135px',
                                errors: '356px'
                            },
                            form: {
                                defaultText: {
                                    registerName: 'Your Name',
                                    registerEmail: 'Your Email',
                                    registerZipcode: 'Zipcode'
                                },
                                validation: {
                                    registerName: [
					{
					    type: 'not[Your Name]',
					    prompt: "Please enter your name."
					},
					{
					    type: 'empty',
					    prompt: 'Please enter your name.'
					}
				],
                                    registerEmail: [
					{
					    type: 'not[Your Email]',
					    prompt: 'Please enter your email address'
					},
					{
					    type: 'empty',
					    prompt: 'Please enter your email address'
					},
					{
					    type: 'email',
					    prompt: 'Please enter a valid email address'
					}
				],
                                    registerZipcode: [
					{
					    type: 'not[Zipcode]',
					    prompt: "Please enter your zipcode."
					},
					{
					    type: 'empty',
					    prompt: 'Please enter your zipcode'
					},
					{
					    type: 'zipcode',
					    prompt: 'Please enter a valid zipcode'
					}
				]
                                }
                            }
                        },
                        locations: {
                            station: {
                                url: '',
                                form: {
                                    defaultText: {
                                        station_address: 'Address',
                                        station_city: "City",
                                        station_zipcode: "Zipcode"
                                    },
                                    validation: {
                                        station_zipcode: [{
                                            type: 'cszip[station_city, station_state]',
                                            prompt: 'Please enter at least a zipcode or city and state'
}]
                                        }
                                    }
                                },
                                plan: {
                                    url: '',
                                    form: {
                                        defaultText: {
                                            plan_start_address: 'Start Address',
                                            plan_start_city: "Start City",
                                            plan_start_zipcode: "Start Zipcode",
                                            plan_end_address: 'End Address',
                                            plan_end_city: "End City",
                                            plan_end_zipcode: "End Zipcode"
                                        },
                                        validation: {
                                            plan_start_zipcode: [{
                                                type: 'cszip[plan_start_city, plan_start_state]',
                                                prompt: 'Please enter at least a starting zipcode or city and state'
}],
                                                plan_end_zipcode: [{
                                                    type: 'cszip[plan_end_city, plan_end_state]',
                                                    prompt: 'Please enter at least an end zipcode or city and state'
}]
                                                }
                                            }
                                        },
                                        weather: {
                                            url: '',
                                            form: {
                                                defaultText: {
                                                    weather_zipcode: 'Zipcode'
                                                },
                                                validation: {
                                                    weather_zipcode: [{
                                                        type: 'empty',
                                                        prompt: 'Please enter a zipcode'
                                                    },
                    {
                        type: 'zipcode',
                        prompt: 'Please enter a valid zipcode'
}]
                                                }
                                            }
                                        },
                                        traffic: {
                                            url: '',
                                            form: {
                                                defaultText: {
                                                    traffic_zipcode: 'Zipcode'
                                                },
                                                validation: {
                                                    traffic_zipcode: [{
                                                        type: 'empty',
                                                        prompt: 'Please enter a zipcode'
                                                    },
                    {
                        type: 'zipcode',
                        prompt: 'Please enter a valid zipcode'
}]
                                                }
                                            }
                                        }
                                    }
                                };

                                var register = {
                                    click: function(event) {
                                        var $content = $(this).siblings('.dropdown');
                                        var $register = $content.parents('.register');
                                        var $errors = $content.find('.errors');
                                        $errors.remove();
                                        $register.find('input').each(function() { $(this).removeClass('warn'); $(this).val(''); $(this).blur(); });

                                        if (!$register.hasClass('open')) {
                                            //track.trackEvent('register', 'open');
                                            $register.addClass('open');
                                            $content
				.protectAnimation()
				.slideDown(300)
			;
                                            $content.animate({ height: config.register.height.normal }, 0);
                                        }
                                        else {
                                            //track.trackEvent('register', 'close');
                                            $register.removeClass('open');
                                            $content
				.slideUp(300, function() {
				    // reset modal
				    $content.find('.dropdown, .thanks, .signup').attr('style', '');
				})
			;
                                            $content.animate({ height: config.register.height.normal }, 0);
                                        }
                                        return false;
                                    },
                                    form: {
                                        success: function() {
                                            // submit form
                                            var $content = $('.register .dropdown');
                                            var $errors = $content.find('.errors');
                                            var $submit = $content.find('.submit');
                                            var $loading = $content.find('.register_loading');
                                            var loadMin = 750;
                                            // show loader, disable hammer click
                                            $submit.hide();
                                            $loading.show();
                                            // clear errors 
                                            $errors.remove();
                                            $content.animate({ height: config.register.height.normal }, 0);
                                            // post ajax
                                            var serializedData = $('.register form').serialize();
                                            var startTime = new Date().getTime();
                                            // nab form and serialize
                                            $.ajax({
                                                url: config.register.url,
                                                data: serializedData,
                                                success: function(response) {
                                                    //track.trackEvent('register', 'success');
                                                    _gaq.push(['_trackEvent', 'register', 'success']);
                                                    var elapsed = new Date().getTime() - startTime;
                                                    var delay = 0;

                                                    // show for at least
                                                    if (elapsed < loadMin)
                                                        delay = loadMin - elapsed;

                                                    setTimeout(function() {
                                                        // hide signup form show thank you
                                                        $content
                            .find('.signup')
                            .css('visibility', 'hidden')
                            .end()
                            .animate({ height: config.register.height.thankYou }, 300, function() {
                                $content.find('.signup').css('visibility', 'visible').hide();
                                $content.find('.thanks').show();
                                $submit.show();
                            })
                        ;
                                                        $loading.hide();
                                                    }, delay);
                                                },
                                                error: function() {
                                                    //track.trackEvent('register', 'error');
                                                    _gaq.push(['_trackEvent', 'register', 'error']);
                                                    $loading.hide();
                                                    $submit.show();
                                                    register.form.failure(['There was a server error processing your request']);
                                                },
                                                dataType: 'json'
                                            });

                                            return false;
                                        },
                                        failure: function(errors) {
                                            //track.trackEvent('register', 'error', 'missing-fields');
                                            var $content = $('.register .dropdown');
                                            var $errors = $content.find('.errors');
                                            // generate errors
                                            var errorList = '';
                                            jQuery.each(errors, function(i, error) {
                                                errorList += '<li>' + error + '</li>';
                                            });
                                            $content.animate({ height: config.register.height.errors }, 300, function() {
                                                // generate list on first error
                                                if ($errors.length == 0) {
                                                    $('<ul/>')
						.attr('class', 'errors')
						.appendTo($content)
					;
                                                }
                                                // Just add new errors
                                                $content.find('.errors')
					.html(errorList)
					.show()
				;
                                            });
                                            return false;
                                        }
                                    },
                                    close: {
                                        click: function() {
                                            $('.register .droplink').click();
                                            return false;
                                        }
                                    }
                                }

                                var contactUs = {
                                    success: function() {
                                        // submit form
                                        var $content = $('#contact');
                                        var $errors = $content.find('.errors-contact');
                                        var $submit = $content.find('.submit');
                                        var $loading = $content.find('.contact_loading');
                                        var loadMin = 1500;
                                        // show loader, disable hammer click
                                        var eh = $submit.data('events').click[0];
                                        $submit.unbind('click', eh);
                                        $submit.css('cursor', 'default');
                                        $loading.show();
                                        // clear errors 
                                        $errors.remove();
                                        // post ajax
                                        var serializedData = $content.find('input').serialize();
                                        serializedData += '&' + $content.find('select').serialize();
                                        serializedData += '&' + $content.find('textarea').serialize();
                                        var startTime = new Date().getTime();
                                        // nab form and serialize
                                        $.ajax({
                                            url: config.contactUs.url,
                                            data: serializedData,
                                            success: function(response) {
                                                //track.trackEvent('contact-us', 'success');
                                                _gaq.push(['_trackEvent', 'contact-us', 'success']);
                                                var elapsed = new Date().getTime() - startTime;
                                                var delay = 0;

                                                // show for at least
                                                if (elapsed < loadMin)
                                                    delay = loadMin - elapsed;

                                                setTimeout(function() {
                                                    // hide signup form show thank you
                                                    $content.find('.submit').hide();
                                                    $content.parent().find('.thankyou').slideDown();
                                                    $loading.hide();
                                                }, delay);
                                            },
                                            error: function() {
                                                //track.trackEvent('contact-us', 'error');
                                                _gaq.push(['_trackEvent', 'contact-us', 'error']);
                                                $loading.hide();
                                                contactUs.failure(['There was a server error processing your request']);
                                            },
                                            dataType: 'json'
                                        });

                                        $submit.bind('click', eh);
                                        $submit.css('cursor', 'pointer');
                                        return false;
                                    },
                                    failure: function(errors) {
                                        //track.trackEvent('contact-us', 'error', 'field-missing');
                                        var $content = $('#contact');
                                        var $errors = $content.find('.errors-contact');
                                        // generate errors
                                        var errorList = '';
                                        jQuery.each(errors, function(i, error) {
                                            errorList += '<li>' + error + '</li>';
                                        });
                                        // generate list on first error
                                        if ($errors.length == 0) {
                                            $('<ul/>')
				.attr('class', 'errors-contact')
				.appendTo($content)
			;
                                        }
                                        // Just add new errors
                                        $content.find('.errors-contact')
			.html(errorList)
			.show()
		;
                                        return false;
                                    }
                                }

                                function initRegister() {
                                    // cache objects
                                    var $register = $('.register');
                                    var $registerLink = $('.register .droplink');
                                    var $registerForm = $('.register form');
                                    var $header = $('#header li').not($register);
                                    var $navigation = $('#navigation li');

                                    var registerConfig = config.register;

                                    $registerLink.click(register.click)

                                    $register
		.find('.dropdown')
			.find('.submit')
				.click(function(e) {
				    //$(this).parents('form').submit();
				    $registerForm.validateForm(registerConfig.form.validation, {
				        onSuccess: register.form.success,
				        onFailure: register.form.failure,
				        inlinePrompt: false
				    });
				    return false;
				})
				.end()
			.find('input')
                .keypress(function(e) {
                    if (e.which == '13') {
                        //validate on hitting enter on inputs or selects or pressing enter key
                        e.stopPropagation();
                        e.preventDefault();
                        $register.find('.dropdown').find('.submit').click();
                    }
                })
				.each(function() {
				    var fieldName = $(this).attr('id');
				    var defaultText = config.register.form.defaultText[fieldName];

				    if (typeof (defaultText) != 'undefined')
				        $(this).inputPrompt(defaultText);

				    $(this).focus(function() { $(this).select(); });
				})
				.end()
			.find('.close')
				.click(register.close.click)
	;
                                }
