$(
    function() {
        var productImgContainer = $( '#product_image_container' );
        if( productImgContainer.length > 0 ) {
            buildProductSlides( productImgContainer );
        }
        
        buildSearchField();
        buildDeliveryLocations();
        detectCalculatorInputs();
        sendDataToGoogle();

        if( IEVersion() <= 6 && IEVersion() != -1 ) {
            // must be placed at the end of the dom:ready or else dynamically placed js items won't respond (i.e. <a>)
            DD_belatedPNG.fix( '#logo, .arrow_buttons, .directions, #phone_button,' +
                           '#menu_indicator, #search_bar, .sidebar, .delivery_button,' +
                           '.slideshow_indicator, #delivery_icon, #truck_table, #calculator-background' );
        }
        
        Shadowbox.init( { handleOversize: "drag", modal: true } );
    }
);


function buildSearchField() {
    if( $( '#s' ) && $( '#s' ).attr( 'value' ) == '' )
    {
        $( '#s' ).attr( 'value', 'search our site' );
    }
    
    $( '#s' ).bind( 
        {
            focus: function()
            {
                if( $( this ).attr( 'value' ) == 'search our site' )
                {
                    $( this ).attr( 'value', '' );
                }
            },
            
            blur: function()
            {
                if( $( this ).attr( 'value' ) == '' )
                {
                    $( this ).attr( 'value', 'search our site' );
                }
            }
        }
    );
    
    $( '#searchsubmit' ).click(
        function()
        {
            $( '#searchform' ).submit();
        }
    );
}


function buildProductSlides( productImgContainer ) {
    var firstImgName = '';
    var productImages = productImgContainer.find( 'img' );
    
    if( productImages.length == 1 ) {
        var firstImg = $( productImages[0] ).attr( 'src' );
        var splitArray = firstImg.split( '/' );
        firstImgName = splitArray[splitArray.length - 1];
    }
    
    if( firstImgName.toLowerCase() == 'blank_l.jpg' ) {
        var relTag = '';
        var imgTitle = 'Image coming soon';
    } else {
        var relTag = '" rel="shadowbox[item]"';
        var imgTitle = 'Click to enlarge';
        var zoomIcon = $( '<div id="zoom_icon"></div>').insertAfter( productImages.last() );
    }
    
    
    var productImagesArray = new Array();
    var largeImg;
    var num = 0;
    
    productImages.siblings().remove( 'br' );
    
    productImages.each(
        function( el )
        {
            num++;
            largeImg = $( this ).attr( 'src' ).replace( '_m', '_l' );
            $( this ).wrap( '<a href="' + largeImg + relTag + ' />' ).attr( 'title', imgTitle );
            
            if( productImages.length > 1 )
            {
                $( 'div#product_info_box' ).append( '<div class="slideshow_indicator slideshow_indicator_off">'+ num +'</div>' );
            }
        }
    ).first().show();
    
    
    var indicator = $( 'div.slideshow_indicator' );
    
    indicator.reverseOrder().each(
        function( index ) 
        {
            $( this ).removeClass( 'slideshow_indicator_on' ).addClass( 'slideshow_indicator_off' );
            $( this ).data( 'imgObj', productImages[index] );
        }
    ).first().removeClass( 'slideshow_indicator_off' ).addClass( 'slideshow_indicator_on' );
    
    indicator.click(
        function()
        {
            indicator.each(
                function() 
                { 
                    $( this ).removeClass( 'slideshow_indicator_on' ).addClass( 'slideshow_indicator_off' );
                    $( $( this ).data( 'imgObj' ) ).hide();
                }
            );
            
            $( this ).removeClass( 'slideshow_indicator_off' ).addClass( 'slideshow_indicator_on' );
            $( $( this ).data( 'imgObj' ) ).show();
        }
    );
        
    zoomIcon.click(
        function() {
            $( 'a[rel="shadowbox[item]"]' ).click();
        }
    );
}


function buildDeliveryLocations()
{
    $( '.delivery_locations' ).click(
        function()
        {
            var location = $( this );
            
            $( '.delivery_locations' ).each(
                function()
                {
                    $( this ).removeClass( 'current_location' );
                }
            );
            
            $( '.zones' ).each(
                function()
                {
                    $( this ).hide();
                }
            );
            
            $( '.pricing_chart' ).each(
                function()
                {
                    $( this ).hide();
                }
            );
            
            location.addClass( 'current_location' );
            
            if( location.hasClass( 'southfield_locations' ) )
            {   
                $( '#pricing_chart_southfield' ).show();
                $( '#zone_chart_southfield' ).show();
            }
            else if ( location.hasClass( 'other_locations' ) )
            {
                $( '#pricing_chart_other' ).show();
                $( '#zone_chart_other' ).show();
            }
            
            
            return false;
        }
    );
    
    
    $( '.zone' ).click(
        function()
        {
            var zone = $( this );
            var zoneColor = '#FAEC85';
        
            $( '.zone' ).css( 'background', 'none' );
            
            if( zone.hasClass( 'local' ) )
            {
                $( '.local' ).css( 'background', zoneColor );
            }
            else if ( zone.hasClass( 'zone1' ) )
            {
                $( '.zone1' ).css( 'background', zoneColor );
            }
            else if ( zone.hasClass( 'zone2' ) )
            {
                $( '.zone2' ).css( 'background', zoneColor );
            }
            else if ( zone.hasClass( 'zone3' ) )
            {
                $( '.zone3' ).css( 'background', zoneColor );
            }
            else if ( zone.hasClass( 'zone4' ) )
            {
                $( '.zone4' ).css( 'background', zoneColor );
            }
            else if ( zone.hasClass( 'zone5' ) )
            {
                $( '.zone5' ).css( 'background', zoneColor );
            }
        }
    );
}


function detectCalculatorInputs()
{
    $( '.calculator-inputs' ).keyup(
        function( evt )
        {
            // take only numeric keys
            var charCode = ( evt.which ) ? evt.which : event.keyCode;
            if ( charCode > 31 && ( charCode < 48 || charCode > 57 ) && ( charCode < 96 || charCode > 105 ) )
            {
                $( this ).attr( 'value', '' );
                return;
            }
            
            if( $( this ).hasClass( 'rect-area' ) )
            {                    
                materialForRectArea( $( '.rect-area' ), $( '#rect-result' ), 3 );
                return;
            }
            
            
            if( $( this ).hasClass( 'cir-area' ) )
            {
                materialForCircArea( $( '#cir-diameter' ).attr( 'value' ), $( '#cir-depth' ).attr( 'value' ), $( '#cir-result' ) );
                return;
            }
        }
    );
}


function materialForRectArea( calType, resultField, fieldNum )
{
    var totalArray = [];
    var total = 1;
                    
    calType.each(
        function()
        {
            if ( $( this ).attr( 'value' ) != '' )
            {
                totalArray.push( $( this ).attr( 'value' ) );
            }
        }
    );
    
    //for( var i in totalArray ) // borks in IE8
    for( var i = 0; i < totalArray.length; i++ )
    {
        total *= totalArray[i];
    }

    total = total / 12 / 27;
                            
    if( isNaN( total ) || total == 0 || totalArray.length < fieldNum )
    {
        resultField.html('');
    }
    else 
    {
        resultField.html( 'You need <span class="result-total">' + Math.round( total * 100 ) / 100 + '</span> cubic yards<span class="asterisk">*</span> ' );
    }
}


function materialForCircArea( diameter, depth, resultField )
{
    var area = Math.pow( parseFloat( diameter / 2 ), 2 ) * Math.PI
    var total = area * parseFloat( depth ) * 144 / 46656;
        
    if( isNaN( total ) || total == 0 )
    {
        resultField.html('');
    }
    else 
    {
        resultField.html( 'You need <span class="result-total">' + Math.round( total * 100 ) / 100 + '</span> cubic yards<span class="asterisk">*</span> ' );
    }
}


function sendDataToGoogle() {
    $( '.analytics' ).click(
        function() {
            var title = $( this ).attr( 'title' );
            console.log( title );
            if( typeof( _gaq ) != 'undefined' ) {
                _gaq.push( ['_trackEvent', 'UserClick', title] );
            }
        }
    );
}


function IEVersion() {
    return ( navigator.appName == 'Microsoft Internet Explorer' ) ? parseFloat( ( new RegExp( "MSIE ([0-9]{1,}[.0-9]{0,})" ) ).exec( navigator.userAgent )[1] ) : -1;
};



$.fn.reverseOrder = function() {
	return this.each(function() {
		$(this).prependTo( $(this).parent() );
	});
};
