/**
 * Mutes firebug console code and errors on browsers where firebug is not installed
 */
if (!window.console || !console.firebug) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", 
    "groupCollapsed", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) {
        window.console[names[i]] = function() {};
    }
}
///**
// * Mutes google analytics event tracking. GA won't be present on the admin side, so pageTracker._trackEvent will throw errors.
// */
//if (!window.pageTracker) {
//    var trackers = ["_trackEvent"];
//    window.pageTracker = {};
//    for (var pti = 0; pti < trackers.length; ++pti) {
//        window.pageTracker[trackers[pti]] = function() {};
//    }
//}

// Parse the date and make the minutes 23:59:59
function dateParse(s) {
    var dateNew = new Date();
    var dateParts = s.split('/');

    if (dateParts[2].length == 2)
        dateParts[2] = '20' + dateParts[2];
        
    var dateAdjusted = (dateParts[0]) +'/'+(dateParts[1])+'/'+(dateParts[2])+' 23:59:59';
    dateNew.setTime(Date.parse(dateAdjusted));
    
    return dateNew;
}

function submitCTA() {
    
    // Cache some shyte
    var valZip = $.trim($('.mainCTAZip').val());
    var valDate = $('.mainCTADate').val();
    var CTAErrorList = $('.mainCTAValidationMessages');
    var CTAErrorListContainer = $('.mainCTAValidationMessagesContainer');
        
    // Valid by default
    var validCTA = true;
    $('input.invalid').removeClass('invalid');
    CTAErrorListContainer.hide();
    CTAErrorList.children().remove();	
    
    // Zip code blank?
    if ((valZip === '') || (valZip == 'zip code')) {
        CTAErrorList.append('<li>Doh! Please fill in a <strong>zip code</strong>.</li>');
        //pageTracker._trackEvent('Jan2010Funnel', 'Error', 'CCFormStateInvalid');
        $('.mainCTAZip').addClass('invalid');
        validCTA = false;
        LogValidationError('[mainCTA] Zip code was blank');
    }
    
    // Zip code valid?
    var regexZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    if ( !regexZip.test( $.trim(valZip) ) )  {
        CTAErrorList.append('<li>Please enter a valid <strong>zip code</strong>.</li>');
        //pageTracker._trackEvent('Jan2010Funnel', 'Error', 'CCFormInvalidCardNum'); 
        $('.mainCTAZip').addClass('invalid');
        validCTA = false;
        LogValidationError('[mainCTA] Zip code wasnt valid (' + valZip + ')');
    }

    // Date field blank?
    if ((valDate === '') || (valDate == 'mm/dd/yyyy')) {
        CTAErrorList.append('<li>You forgot to fill in a <strong>date</strong>!</li>');
        //pageTracker._trackEvent('Jan2010Funnel', 'Error', 'CCFormStateInvalid');
        $('.mainCTADate').addClass('invalid');
        validCTA = false;
        LogValidationError('[mainCTA] Date field was blank');
    }
    
    // Date in the past?
    var desiredDate = dateParse(valDate);
    var currentDate = new Date();
    if (desiredDate < currentDate) {
        CTAErrorList.append('<li>Great scott, Marty!&hellip; <strong>This job can\'t happen in the past!</strong>. Try a date in the <strong>future</strong>.</li>');
        //pageTracker._trackEvent('Jan2010Funnel', 'Error', 'CCFormStateInvalid');
        $('.mainCTADate').addClass('invalid');
        validCTA = false;
        LogValidationError('[mainCTA] Date field was in the past (' + valDate + ')');
    }
    
    // Prep date for url injection
    var dateTrim = $.trim(valDate).split('/');
    
    if ( validCTA === false ) {		
        CTAErrorListContainer.show();
    } else {
        window.location = globalBaseHttps + '/Checkout/HelperList.aspx?ZipCode=' + encodeURIComponent(valZip) + '&Date=' + encodeURIComponent(dateTrim[0] + '-' + dateTrim[1]+ '-' + dateTrim[2]) + '&CategoryID=' + encodeURIComponent($('.mainCTAType').val());
    }
    return false;
}

// Form results
function formResultsMessage(style, content) {
    if ( style == 'buttonReSubmit') {
        $('.formActions input[type="submit"]').val(content);
    }
    if ( style == 'defaultSuccess') {
        $('.defaultActions').hide();
        $('.formActions').addClass('formActionsSuccess');
        $('.actionStatus').addClass('actionStatusSuccess').text(content).fadeIn();
    }
    if (style == 'largeSuccess') {
        $('.formContent, #errorList, .formActions').hide();
        $('.formStatus').html(content).addClass('formLargeSuccess').comboToggle( 1000 );
        $.scrollTo( '.formWrap', 1000);
    }
}

function formWorking(type, message) {
    $('.defaultActions').hide();
    if (type == 'actionStatusWorking') {
        $('.actionStatus').addClass('actionStatusWorking').text(message).fadeIn();
    }
    if (type == 'actionStatusRedo') {
        $('.actionStatus').hide();
        $('.formActions, .defaultActions').show();
    }
}

/*	DOM-READY FUNCTION
-------------------------------------------------------------- */
$(function() {
    
    var isIE6 = false;
    
    // Detect IE and set a global variable
    if ( $.browser.className == 'msie6' ) {
        isIE6 = true;
        $.ajax({ url: '/static/xhr/global/ie6-warning.html', success: function(html){ $('body').prepend(html); } });
    }

    $('.valueHold').valueHold();

    $('.mainCTASubmit').click(function() {
        submitCTA();
        return false;
    });

    $('.mainCTA input').focus(function() {
        $(this).removeClass('invalid');
        return false;
    });

    // Hold values for call-to-action fields
    $('.mainCTADate').datepicker();

    // CLick the calendar icon on the date text input.
    $('.mainCTADateBug').click(function() {
        $('.mainCTADate').focus();
        return false;
    });
    
    // Track outbound links with rel="outbound" (for analytics)
    $("a[rel*='outbound']").click(function(){
        _gaq.push(['_trackPageview','/outgoing/'+ $(this).attr('href')]);
    });
    

    // 
    // New Form Styles/Validation 7-13-2010
    //
    if ( $('.formWrap').length > 0 ) {
        
        // Highlight .formItem sections when their child elements are focused. (ala woofu)
        $('.formItem *').bind('focus click', function() {
            // If you're clicking on something within the current .formItem, don't do the class switch
            var clicked = $(this).closest('.formItem');
            if (clicked.hasClass('.focused')) {
                return;
            }
            // remove the class from all .formItem
            $(".formItem").removeClass('focused');
            // ...and add the class to the one that was clicked.
            if (!clicked.hasClass('invalid')) {
                clicked.addClass('focused');
            }
        }).blur(function() {
            $(".formItem").removeClass('focused');
        });
        
        if ( $('.formActions.stickyActions').length > 0) {
            // Save poisition of the .formActions
            var fformActions = $('.formActions');
            var formPos = Math.floor(fformActions.offset().top);
            var formHeight = fformActions.height();
            var formWidth = fformActions.width();
            // Move .formActions if it is below the fold
            function stickyFormActions() {
                var theFold = $(window).height() + $(window).scrollTop();
                if (formPos > (theFold - formHeight - formHeight)) {
                    fformActions.addClass('sticky');
                    fformActions.css({
                        width: formWidth,
                        height: formHeight
                    });
                } else {
                    fformActions.removeClass('sticky');
                }
            }
            /// When on-dom-ready fires
            stickyFormActions();
            // Upon scrolling,
            $(window).scroll(stickyFormActions).resize(stickyFormActions);
        }
    }
    
    // Fix fancy buttons in IE6
    if ( isIE6 ) {
        $('.fancyButton.green').css('backgroundColor','#6CA04E');
        $('.fancyButton.blue').css('backgroundColor','#2daebf');
        $('.fancyButton.red').css('backgroundColor','#e33100');
        $('.fancyButton.magenta').css('backgroundColor','#a9014b');
        $('.fancyButton.orange').css('backgroundColor','#ff5c00');
        $('.fancyButton.yellow').css('backgroundColor','#ffb515');
    }
    
    // Fix IE6 & IE7 lack of attribute selectors
    // if ( isIE6 ) {
    // 	$('.formItem input[type="text"]').addClass('typeText');
    // }
    
    //$('div').each(function() {
    //	$(this).html($(this).html().replace('Moving', 'XXXXXXXX'));
    //});

});

/*	WINDOW LOADED FUNCTION
-------------------------------------------------------------- */
$(window).load(function() {
    $('body *').replaceText(/(moving)(-|\s|_|&nbsp;)*(help)/gi, '$1$2labor$2$3');		
});


