// $Id: gearfoo.js 45 2011-05-30 23:12:00Z khalib $

var reviewRatingChoice = 0;
var companies = Array()

$(document).ready(function() {
    $('.shadow').each(function() {
        var classes = $(this).attr('class');
        $(this).before('<div class="image-shadow ' + classes.replace('frame', '') + '"></div>');
    });
    
    // PinPoint
    /*
    var imageKey = $('.gearspotting-image').attr('id').replace('image-', '');
    $('.gearspotting-image').pinPoint({ imageKey: imageKey });
    */
    
    // Generate rating stars
    //generateRatingStars();
    
    // Product review rating stars selector
    $('.rating-wrapper .rating').live('mousemove', function(e) {
        var position = e.pageX - this.offsetLeft;
        
        gearfooClearReviewRating(this);
        $(this).addClass('rating-' + gearfooRatingStarPositionValue(this, e) + '-0');
    });
    
    $('.rating-wrapper .rating').live('click', function(e) {
        reviewRatingChoice = gearfooRatingStarPositionValue(this, e);
        $(this).parent('.rating-wrapper').find(':radio[value=' + reviewRatingChoice + ']').attr('checked', true);
    });
    
    $('.rating-wrapper .rating').live('mouseover', function() {
        gearfooClearReviewRating(this);
    });
    
    $('.rating-wrapper .rating').live('mouseout', function() {
        gearfooClearReviewRating(this);
        $(this).addClass('rating-' + reviewRatingChoice + '-0');
    });
    
    /**
     * Product page user review form
     */
    // Hide review textarea and submit button
    $('.product-page #user-review-form .field-wrapper-review, .product-page #user-review-form .submit-button').hide();
    
    $('.product-page #user-review-form .rating').live('click', function() {
        $('.product-page #user-review-form .field-wrapper-review').slideDown(500);
        $('.product-page #user-review-form .submit-button').slideDown(500);
        
        return false;
    });
    
    // Submit user review
    $('.product-page #user-review-form .submit-button').live('click', function() {
        data = {};
        data['rating'] = $('.product-page #user-review-form input[name="rating"]:checked').val();
        data['review'] = $('.product-page #user-review-form textarea[name="review"]').val();
        
        $('.product-page .user-review-form-wrapper').loader({ size: 'medium' });
        
        $.ajax({
            type: 'POST',
            url: document.URL,
            data: data,
            success: function(response) {
                $('.product-page .user-review-form-wrapper').hide(1, function() {
                    if (response['status'] == true) {
                        
                    }
                    else {
                        
                    }
                    $(this).html(response['data']).show(1, generateRatingStars()).statusMessage({ message: response['status_message'], type: response['status_type'] });
                });
            }
        });
        
        return false;
    });
    
    // Company drop-down replacement with autofill textbox
    if ($('#id_company').length > 0) {
        $('#id_company')
            .wrap('<div class="company-select-wrapper">')
            .before(function () {
                var index = 0;
                $('#id_company > option').each(function (i) {
                    if ($(this).val() != '') {
                        companies[index++] = $(this).text();
                    }
                })
                companyName = ($('#id_company > option:selected').val().length != 0) ? $('#id_company > option:selected').text() : '';
                return '<input id="id_company" name="company" type="text" value="' + companyName + '">';
            }).remove();

        $('#id_company').autocomplete(companies);
    }
    
    // Add a flag to denote javascript is enabled to all forms
    $('form').append('<input id="javascript-enabled" name="javascript-enabled" type="hidden" value="true">');
    
    // Product Image Cropper
    if ($('#product-image-crop') > 0) {
      $('#product-image-crop').Jcrop({
          //aspectRatio: 300/230,
          onChange: showCoords
      });
    }
    
    $('form').has('.image-cropper').append('<input type="hidden" size="4" id="x1" name="x1" /><input type="hidden" size="4" id="y1" name="y1" /><input type="hidden" size="4" id="x2" name="x2" /><input type="hidden" size="4" id="y2" name="y2" /><input type="hidden" size="4" id="w" name="w" /><input type="hidden" size="4" id="h" name="h" />');
    //$('#product-image-crop').after('x1<input type="text" size="4" id="x1" name="x1" /><br>y1<input type="text" size="4" id="y1" name="y1" /><br>x2<input type="text" size="4" id="x2" name="x2" /><br>y2<input type="text" size="4" id="y2" name="y2" /><br>w<input type="text" size="4" id="w" name="w" /><br>y<input type="text" size="4" id="h" name="h" />');
    
    // User Picture Image Cropper
    if ($('#user-picture-crop') > 0) {
      $('#user-picture-crop').Jcrop({
          aspectRatio: 1/1,
          setSelect: [10, 10, 100, 100],
          onChange: showCoords
      });
    }
    
    // Display status message
    if ($('#status-message-bar').html().length > 0) {
        $('.status-message.no-javascript').hide();
        setTimeout(function() {
            $('#status-message-bar, .status-message:not(.no-javascript)').slideDown(500);
            setTimeout(function() {
                $('#status-message-bar, .status-message').slideUp(500);
            }, 4000);
        }, 1000);
    }
});

function showCoords(c) {
    $('#x1').val(c.x);
    $('#y1').val(c.y);
    $('#x2').val(c.x2);
    $('#y2').val(c.y2);
    $('#w').val(c.w);
    $('#h').val(c.h);
    
    if (c.x2 > 100) {
        
    }
}

function gearfooRatingStarPositionValue(thisObj, e) {
    var position = e.pageX - thisObj.offsetLeft;
    var ratingValue = 0;
    
    if (position >= 0 && position <= 28) {
        ratingValue = 1;
    }
    else if (position > 28 && position <= 56) {
        ratingValue = 2;
    }
    else if (position > 56 && position <= 84) {
        ratingValue = 3;
    }
    else if (position > 84 && position <= 112) {
        ratingValue = 4;
    }
    else if (position > 112 && position <= 140) {
        ratingValue = 5;
    }
    
    return ratingValue;
}

function gearfooClearReviewRating(thisObj) {
    $(thisObj).removeClass('rating-1-0')
        .removeClass('rating-2-0')
        .removeClass('rating-3-0')
        .removeClass('rating-4-0')
        .removeClass('rating-5-0');
}

function generateRatingStars() {
    // Generate rating stars
    $('ul:has(.rating-value)').addClass('rating-stars')
        .hide()
        .wrap('<div class="rating-wrapper" />')
        .before(function () {
            ratingValue = ($(this).find(':checked').val() == null) ? 0 : $(this).find(':checked').val();
            return '<div class="rating selector stars-large rating-' + ratingValue + '-0"></div>';
        });
}

function generateLoader(size, text) {
    text = (text) ? text : 'Loading...';
    return '<div class="loader-wrapper"><div class="loader ' + size + '"> </div><div class="text">' + text + '</div></div>';
}

/**
 * AJAX loader animation adder.
 */
(function($) {
    $.fn.loader = function(options) {
        var settings = {
            'text': 'Loading...',
            'size': 'small',
            'method': 'html',
            'class': 'pad-top',
        };
        
        return this.each(function() {
            if (options) {
                $.extend(settings, options);
            }
            
            eval('$(this).' + settings['method'] + '(\'<div class="loader-wrapper ' + settings['class'] + '"><div class="loader ' + settings['size'] + '"></div><div class="text">' + settings['text'] + '</div></div>\')');
        });
    };
})(jQuery);

/**
 * Status Message Overlay
 */
(function($) {
    $.fn.statusMessage = function(options) {
        var settings = {
            'type': 'confirmation',
            'message': ''
        }
        
        return this.each(function() {
            if (options) {
                $.extend(settings, options);
            }
            
            $('#status-message-bar, .status-message').removeClass('confirmation').removeClass('error').addClass(settings['type']).html(settings['message']);
            setTimeout(function() {
                $('#status-message-bar, .status-message:not(.no-javascript)').slideDown(500);
                setTimeout(function() {
                    $('#status-message-bar, .status-message').slideUp(500);
                }, 4000);
            }, 1000);
        });
    }
})(jQuery);

/**
 * Gearspotter picture pinpointer
 */
(function($) {
    $.fn.pinPoint = function(options) {
        var settings = {
            'pinOffsetX': 10,
            'pinOffsetY': 35,
            'imageKey': ''
        }
        
        return this.each(function() {
            if (options) {
                $.extend(settings, options);
            }
            
            var x = 0;
            var y = 0;
            var x_coord = 0;
            var y_coord = 0;
            var width = 0;
            var height = 0;
            var index = 0;
            
            // User clicks within an image
            $(this).click(function(e) {
                var $image = $(this);
                
                width = $(this).width();
                height = $(this).height();
                x_coord = e.pageX - $(this).offset().left;
                y_coord = e.pageY - $(this).offset().top;
                x = x_coord / width;
                y = y_coord / height;
                
                // Get the image tag form
                $.ajax({
                    type: 'POST',
                    url: '/images/ajax/form/tag/',
                    data: { imageKey: settings['imageKey'] },
                    success: function(response) {
                        var form = response.data;
                        var form_output = '<div id="popup-' + index +'" class="popup" style="top: ' + (y_coord - settings['pinOffsetY']) + 'px; left: ' + (x_coord - settings['pinOffsetX']) + 'px;"><div id="tag-form-' + index + '" class="tag-form">' + form + '</div></div>';
                        var pin_output = '<div id="pinpoint-pin-' + index + '" class="pinpoint-pin" style="top: ' + (y_coord - settings['pinOffsetY']) + 'px; left: ' + (x_coord - settings['pinOffsetX']) + 'px;"></div>';
                        $image.after(form_output + pin_output);
                        var $form = $('#tag-form-' + index);
                        var $pin = $('#pinpoint-pin-' + index);
                        $('#popup-' + index).attr('style', 'top: ' + (y_coord - settings['pinOffsetY'] - $pin.height() - $form.height()) + 'px; left: ' + (x_coord - settings['pinOffsetX'] - ($form.width()/2)) + 'px');
                        
                        // Form submit handler
                        $('#tag-form-' + index + ' #edit-submit').live('click', function() {
                            $form = $('#tag-form-' + index + ' form');
                            $form.find('#id_x').val(x);
                            $form.find('#id_y').val(y);
                            
                            $.ajax({
                                type: 'POST',
                                data: $('#tag-form-' + index + ' form').serialize(),
                                url: '/images/ajax/tag/create/',
                                success: function(response) {
                                    $('#popup-' + index).remove();
                                }
                            });
                            
                            return false;
                        })
                    }
                });
                index++;
            })
        });
    }
})(jQuery);


/*
// Display status message
if ($('#status-message-bar').html().length > 0) {
    $('.status-message.no-javascript').hide();
    setTimeout(function() {
        $('#status-message-bar, .status-message:not(.no-javascript)').slideDown(500);
        setTimeout(function() {
            $('#status-message-bar, .status-message').slideUp(500);
        }, 4000);
    }, 1000);
}
*/
