var emailPattern = /.+@.+\..+/;

var contactFunctions = {
	getStates: function(country, fnCallback){
		$.getJSON('/_inc/_ajx/ajxQuoteActions.php', {
            action: 'contact_geography',
            jCountryCode: country
        }, function(data) {
            var stateField = $('.input_state');
            var intStateField = $('.input_state_international');
            if ($(data.states).length) {
                var currentState = stateField.val();
                intStateField.attr('disabled', 'disabled').hide();
                stateField.addClass('required').removeAttr('disabled').parents('.input_required_wrapper').show();
                stateField.empty().append($('<option value="0">').html('Select a State'));
                $(data.states).each(function() {
                    stateField.append($('<option value="' + this.state_short + '">').html(this.state_name));
                });
                stateField.val(currentState = 0 ? intStateField.val() : currentState);
            } else {
                // If a state value has already been selected add it to the new text field (in case you accidentally select the wrong country)
                if (stateField.val() !== '0') {
                    intStateField.val(stateField.val());
                }
                stateField.removeClass('required').attr('disabled', 'disabled').parents('.input_required_wrapper').hide();
                intStateField.removeAttr('disabled').show();
            }
            if ($.isFunction(fnCallback)) {
                fnCallback.call(this, data);
            }
        });
	}
};

var quoteFunctions = {
	validateForm: function(vForm) {
        $('.input_error').remove();
        $('.required').removeClass('form_not_valid');
        var isValid = 1;
        var thisForm = $(vForm).attr('id');
        $(vForm).find('.required').each(function() {
        	var thisInput = this;
            switch ($(this).attr('name')) {
            case 'FirstName':
            case 'LastName':
            case 'rfqName':
                // Checks for at least one non-space character
                if (!$(this).val().match(/^.+[\S].+$/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please enter a Name'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'ActivityDate':
            	// Checks for at least one non-space character
                if (!$(this).val().match(/^.+[\S].+$/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please select a Date'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
            	break;
            case 'Email':
            case 'rfqEmail':
                // Checks for an email address of anything@anything.anything
                if (!$(this).val().match(/.+@.+\..+/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please enter an Email Address'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'Phone':
            case 'rfqPhone':
                // Checks for at least one non-space character
                if (!$(this).val().match(/^.+[\S].+$/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please enter a Phone Number'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'AccountName':
            case 'rfqCompany':
                // Checks for at least one non-space character
                if (!$(this).val().match(/^.+[\S].+$/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please enter a Company'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'MailingStreet':
            case 'BillingStreet':
            case 'rfqAddress':
                // Checks for at least one non-space character
                if (!$(this).val().match(/^.+[\S].+$/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please enter an Address'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'MailingCity':
            case 'BillingCity':
            case 'rfqCity':
                // Checks for at least one non-space character
                if (!$(this).val().match(/^.+[\S].+$/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please enter a City'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'MailingState':
            case 'BillingState':
            case 'rfqStateID':
                // Checks for a state value
                if ($(this).val() === '0') {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please select a State'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'MailingPostalCode':
            case 'BillingPostalCode':
            case 'rfqPostalCode':
                // Checks for at least one non-space character
                if (!$(this).val().match(/^.+[\S].+$/)) {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please enter a Postal Code'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            case 'MailingCountry':
            case 'BillingCountry':
            case 'rfqCountryID': 
                // Checks for a Country value
                if ($(this).val() === '0') {
                    $(this).addClass('form_not_valid');
                    $(this).after($('<div class="input_error">').html('Please select a Country'));
                    _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                    isValid = 0;
                }
                break;
            }
        });
        return isValid;
    },

    /*
checkInput: function(thisInput){
        var thisForm = $(thisInput).parents('form').attr('id');
        switch ($(thisInput).attr('id'))
        {
        case 'summary_email':
            var emailVal = $(thisInput).attr('value');
            if (!emailPattern.test(emailVal)){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter a valid email address.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_name':
            if ($(thisInput).attr('value') == ''){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your name.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_company':
            if ($(thisInput).attr('value') == ''){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your company.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_title':
            if ($(thisInput).attr('value') == ''){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your title.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_address':
            if ($(thisInput).attr('value') == ''){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your address.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_city':
            if ($(thisInput).attr('value') == ''){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your city.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_state':
            if ($(thisInput).attr('value') == 0){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your state/province.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_postal':
            if ($(thisInput).attr('value') == ''){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your postal code.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }
            break;
        case 'summary_phone':
            if ($(thisInput).attr('value') == ''){
                $(thisInput).addClass('form_not_valid');
                $(thisInput).next('.input_error').html('Please enter your phone number.').show();
                _gaq.push(['_trackEvent', 'Forms', thisForm, 'alert_' + $(thisInput).attr('id')]);
                return false;
            }

        }
    },
*/

    checkEmail: function(data, thisForm){
        if (data.resultCount == 0){
            if ($('.form_new_user', thisForm).css('display') == 'none'){
                $('#summary_state').show();
                $('#form_new_alert', thisForm).show();
                $('.form_new_user', thisForm).show('blind', null, 500);
                $('.input_name,.input_company,.input_title,.input_address,.input_city,.input_state,.input_postal,.input_country,.input_phone', thisForm).addClass('required');
            }
        } else if ($('.form_new_user', thisForm).css('display') != 'none'){
            $('.form_new_user', thisForm).toggle('blind', null, 500);
            $('.input_name,.input_company,.input_title,.input_address,.input_city,.input_state,.input_postal,.input_country,.input_phone', thisForm).removeClass('required');
        }

    }
};

var bannerFunctions = {
    activeFrame: 0,
    bannerContentsWidth: 960,
    bannerTransitionTime: 250,
    bannerTimeoutLength: 7000,
    frameLength: null,
    frameRotateTimer: null,
    frameTimeoutLength: 7000,
    goToFrameTimer: null,

    frameRotate: function(){
        if (bannerFunctions.activeFrame >= bannerFunctions.frameLength - 1){
            bannerFunctions.goToFrame(0);
        }
        else{
            bannerFunctions.goToFrame(bannerFunctions.activeFrame + 1);
        }
    },
    goToFrame: function(frameNumber){
        clearTimeout(bannerFunctions.frameRotateTimer);
        bannerFunctions.frameRotateTimer = setTimeout('bannerFunctions.frameRotate()', bannerFunctions.bannerTimeoutLength);
        bannerFunctions.activeFrame = frameNumber;
        $('.promo_bookmarks').removeClass('promo_bookmarks_active');
        $('#promo_wrapper').stop();
        $('#promo_wrapper').animate({
            left: '-' + frameNumber * bannerFunctions.bannerContentsWidth + 'px'
        },
        bannerFunctions.bannerTransitionTime);
        $('.promo_bookmarks').eq(frameNumber).addClass('promo_bookmarks_active');
    }
};

$(document).ready(function(){

	//Product page configurations
	
	$('.product_request_configuration').click(function(e){
		e.preventDefault();
		$('li').removeClass('ui-tabs-selected').removeClass('ui-state-active');
		$('div.ui-tabs-panel').addClass('ui-tabs-hide');
		$('a[href=#tabs-7]').parents('li').addClass('ui-tabs-selected').addClass('ui-state-active');
		$('div#tabs-7').removeClass('ui-tabs-hide');
	});

    ////////////////////////////////////
    // Homepage Banner
    ////////////////////////////////////
    bannerFunctions.frameLength = $('.promo_frame').length;
    var bannerBookmarks = $('<div id="promo_bookmarks_wrapper">');

    // Initialize banner bookmarks 
    for (i = 1; i <= bannerFunctions.frameLength; i++){
        bannerBookmarks.append($('<div class="promo_bookmarks">'));
    }
    bannerBookmarks.appendTo('#promo');

    // Banner bookmark listener
    $('.promo_bookmarks').live('click',
    function(){
        var thisBookmark = $(this).index('.promo_bookmarks');
        bannerFunctions.goToFrame(thisBookmark);
    });

    //Start the Timer
    //bannerFunctions.goToFrameTimer = setTimeout('bannerFunctions.frameRotate()', bannerFunctions.bannerTimeoutLength);
    bannerFunctions.goToFrame(0);

    ////////////////////////////////////
    // Form Submit Stuff
    ////////////////////////////////////
    var keyupTimeout;

    //Don't hide additional information if form is a resubmit
    if (!$('.form_new_user').hasClass('form_resubmit')){
        $('.form_new_user').hide();
    }

    // Validate email as entered
    $('.input_email').live('keyup blur',
    function(e){
    	var thisInput = this;
        var thisForm = $(thisInput).parents('form');
        window.clearTimeout(keyupTimeout);
        keyupTimeout = window.setTimeout(function(){
            if (emailPattern.test($(thisInput).val())){
                $(thisInput).addClass('quote_input_loading');
                $.getJSON("/_inc/_ajx/ajxQuoteActions.php", {
                    action: 'validate',
                    rfqEmail: $(thisInput).val()
                },
                function(data){
                	$(thisInput).removeClass('quote_input_loading');
                    quoteFunctions.checkEmail(data, thisForm);
                });
            }
        },
        500);
    });

    //Clear quote page comments on click
    $('.input_comments').focus(function(){
        if ($(this).attr('value') == 'Enter additional comments here...'){
            $(this).attr('value', '');
        }
    });

    //Stuff to do on Form Submit
    $('form').submit(function(e){
        $('.input_error').hide();
        thisForm = this;
        _gaq.push(['_trackEvent', 'Forms', $(thisForm).attr('id'), 'submit_' + $(thisForm).attr('id')]);

        //Handle Comment boxes per form
        switch ($(thisForm).attr('id')) {
        case 'form_summary':
            if ($('#summary_comments').html() == 'Enter additional comments here...'){
                $('#summary_comments').html('');
            }
        }

        //Validate Form and track alerts in GA
        if (quoteFunctions.validateForm(this) == 0){
            e.preventDefault();
        }
    });

    $('.secondary_item').click(function(){
        $.post("../../_inc/_ajx/ajxQuoteActions.php?action=additem", {
            itemID: $(this).attr('id')
        },
        function(data){
            if (data.length == 0){
                $('#summary_alerts').animate({
                    opacity: 1
                },
                750).html('Your quote has been updated!').delay(1500).animate({
                    opacity: 0
                },
                750);
            } else{
                $('#summary_alerts').animate({
                    opacity: 1
                },
                750).html(data).delay(1500).animate({
                    opacity: 0
                },
                750);
            }
        });
    });

    //Track changes to form inputs
    $('input').change(function(){
        var thisID = $(this).attr('id');
        var thisForm = $(this).parents('form').attr('id');
        _gaq.push(['_trackEvent', 'Forms', thisForm, 'change_' + thisID]);

        if ($(this).hasClass('input_required')){
            quoteFunctions.checkInput(this);
        }
    });

    // CREATE STATE SELECT DROPDOWN
    // $('li').add('<select class="input_state" id="summary_state" name="rfqStateID">');
    $('.input_quantity').change(function(){
        var nQid = $(this).attr('id');
        var nQty = $(this).val();

        $.post("../../_inc/_ajx/ajxQuoteActions.php?action=qty", {
            itemQty: nQty,
            quoteID: nQid
        },
        function(data){
            if (data.length == 0){
                $('#summary_alerts').animate({
                    opacity: 1
                },
                750).html('Your quote has been updated!').delay(1500).animate({
                    opacity: 0
                },
                750);
            }
        });
    });

	$('.input_country').change(function(){
		contactFunctions.getStates($(this).val(), function(){
		});
	});

    /*
//Something about states...	
    $('.input_country').change(function(){
        $.post("../../_inc/_ajx/ajxQuoteActions.php?action=states", {
            rfqCountryID: $(this).val()
        },
        function(data){
            if (data.length != 0){
                //$('#rfqStateName').hide();
                $('#form_state').show();
                $('.input_state').show();
                $('.input_state').html(data);
            } else{
                $('.input_state').hide();
                $('#form_state').hide();
                //$('#rfqStateName').show();
            }
        });
    });
*/
});
