jQuery(document).ready(function($) {

    // set options for ajaxing the testimonial form
    var options = {
        beforeSubmit: showRequest,
        success: showResponse
    };

    // prepare the testimonial form
    if ($('#contact_form').length) {
        $('#contact_form').ajaxForm(options);
    }

    // prepare the image fader on the home page
    if ($('#splash').length) {
        $('#splash').cycle({
            fx: 'fade',
            delay: -3000,
            timeout: 6000,
            speed: 1700,
            pause: true
        });
        $('#frame_drops').wait(1.5).then.fadeOut('slow');
    }

    // use fancybox to show a larger view of each product
    if ($('#products').length) {
        $('a.zoom').fancybox({
            'zoomSpeedIn': 300,
            'zoomSpeedOut': 300,
            'overlayShow': false
        });
        $('a.plus').click(function() {
            $(this).next().click();
            return false;
        });

        $(window).resize(function() {
            var width = $(window).width();
            var diff = width - 980;
            var move = diff / 2;
            $('#PPMiniCart form').animate({
                'right': move
            },
            100);
        });

        // show the tooltips for the shipping links
        $('img[title]').qtip({
            show: 'mouseover',
            hide: 'mouseout',
            style: {
                width: 130,
                padding: 5,
                background: '#EFEFEF',
                color: '#555555',
                textAlign: 'center',
                border: {
                    width: 3,
                    radius: 5
                },
                tip: true,
                name: 'light'
            },
            position: {
                corner: {
                    target: 'topLeft',
                    tooltip: 'bottomRight'
                }
            }
        });

        // mail to link for more product information
        $('input.purchase_contact').click(function() {
            var product = $(this).val();
            var email = 'bobt@americont.com';
            var subject = 'Information Request from Website - Product ' + product;
            var mailto_link = 'mailto:' + email + '?subject=' + subject;
            win = window.open(mailto_link, 'emailWindow');
            if (win && win.open && !win.closed) win.close();
        });
    }

    // if we are on the product list page for editing - use colorbox for confirmation
    if ($('a.delete-link').length) {
        $('a.delete-link').colorbox({
            transitionSpeed: '100',
            opacity: .5
        },
        function() {
            $('#cancel').click(function() {
                $.fn.colorbox.close();
            });
            $('#delete-confirm').click(function() {
                var id = $('#deleteID').val();
                removeItem(id);
            });
        });
    }

    // set up the uploader if we are in edit mode
    if ($('#img-upload').length) {
        $.fn.submitSlide();
    }
});

// functions for ajax forms
function showRequest(formData, jqForm, options) {
    if (ValidateForm() == false) {
        return false;
    }
    $('#waiting').slideDown(400);
    return true;
}

function showResponse(responseText, statusText) {
    $('#waiting_img').hide();
    $('#thanks').fadeIn();
}

// remove an item from the database
function removeItem(id) {
    $('#confirm-hold').html('<img src="' + global.base + 'assets/_images/ajax-loader-blue.gif"/>');
    $.post(global.base + 'admin/delete_product', {
        id: id
    },
    function(data) {
        $('#modal-content').wait(2).then.html(data);
        $('#line' + id).fadeOut().wait(1).then.remove();
        setTimeout(function() {
            $.fn.colorbox.close();
        },
        5000);
    });
}

// paypal cart settings
var MiniCart = {
    displayEdge: 'R',
    edgeDistance: '25px',
    cookiePath: '/',
    currencySymbol: '$',
    onAddToCart: function(product) {
        //$('span:contains("does not include")').html('DEF Shopping Cart');
        var width = $(window).width();
        var diff = width - 980;
        var move = diff / 2;
        $('#PPMiniCart form').css('right', move);
    },
    onUpdateTotal: function() {
        },
    onCheckout: function() {}
};


// some simple email validation
function echeck(str) {
    var at = '@';
    var dot = '.';
    var lat = str.indexOf(at);
    var lstr = str.length;
    var ldot = str.indexOf(dot);
    if (str.indexOf(at) == -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(at, (lat + 1)) != -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(dot, (lat + 2)) == -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    if (str.indexOf(' ') != -1) {
        alert('Invalid E-mail Address');
        return false;
    }
    return true;
}

// make sure the fields are filled out properly
function ValidateForm() {
    var nameID = $('#name').val();
    if ((nameID == null) || (nameID == '')) {
        alert('Please Enter your First Name');
        $('#name').focus();
        return false;
    }
    var titleID = $('#title').val();
    if ((titleID == null) || (titleID == '')) {
        alert('Please Enter your Title');
        $('#title').focus();
        return false;
    }
    var companyID = $('#company').val();
    if ((companyID == null) || (companyID == '')) {
        alert('Please Enter your Company');
        $('#company').focus();
        return false;
    }
    var emailID = $('#email').val();
    if ((emailID == null) || (emailID == '')) {
        alert('Please Enter your Email Address');
        $('#email').focus();
        return false;
    }
    if (echeck(emailID) == false) {
        $('#email').val('');
        $('#email').focus();
        return false;
    }
    var phoneID = $('#phone').val();
    if ((phoneID == null) || (phoneID == '')) {
        alert('Please Enter your Phone Number');
        $('#phone').focus();
        return false;
    }
    return true;
}

// prepare the image editor for editing after there is already an image for this product
function edit_load()
 {
    $('#edit_image').hover(
    function() {
        $(this).attr('src', global.base + 'assets/_images/pencil_roll.png');
    },
    function() {
        $(this).attr('src', global.base + 'assets/_images/pencil.png');
    }
    );
    $('#edit_image').click(function()
    {
        $('#preview').css('left', '400px').hide();
        $('#form_main').css('left', '-400px');
        $('#preview').animate({
            'left': '400px'
        },
        'fast');
        $('#add_image').animate({
            'left': '0'
        },
        'fast');
        $('#preview-loader,#generate,#info-hold').remove();
    });
}

// main jquery function to handle the sliding proouct editor
$.fn.submitSlide = function(opts)
 {
    // set our global defaults here
    var defaults =
    {
        part_msg: 'Please Enter A Part Number',
        description_msg: 'Please Enter A Description'
    };
    var opts = jQuery.extend(defaults, opts);

    // prepare the uploader to handle our pics
    $("#userfile").uploadify({
        'uploader': global.base + 'assets/_js/uploadify.swf',
        'script': global.base + 'upload/do_upload',
        'cancelImg': global.base + 'assets/_images/cancel.png',
        'buttonImg': global.base + 'assets/_images/browse.png',
        'rollover': true,
        'height': 38,
        'auto': true,
        'multi': false,
        'scriptAccess': 'always',
        'wmode': 'transparent',
        'fileExt': '*.jpg;*.gif;*.png',
        'fileDesc': 'image files',
        'onComplete': fileDone
    });

    // the cancel button on either adding or editing takes the user back to the product list
    $('#cancel_add').click(
    function() {
        window.location = global.base + 'admin/product_list';
    });

    // function to handle the image manipulation and add to the DOM after upload is done
    function fileDone(event, queueID, fileObj, reposnse, data)
    {
        // check to see if there is an image already there - if so let's dump it
        if ($('#product-shot').length)
        {
            $('#form_hold').css({
                'width': '400px'
            });
            $('#preview').show();
            $('#product-shot').remove();
        }
        // resize the image with codeigniter
        $.post(global.base + 'admin/resize', {
            img: fileObj.name
        },
        function(data) {
            $('#pichold h2').after(data);
            edit_load();
        });

        // slide the preview pane into view for confirmation
        $('input#img_name:hidden').val(fileObj.name);
        $('div.upload-container').after('<p id="generate">generating preview... </p><img id="preview-loader" src="' + global.base + 'assets/_images/ajax-loader.gif"/>').hide();
        $('#add_image').wait(2).then.animate({
            'left': '-400px'
        },
        'fast');
        $('#preview').wait(2).then.animate({
            'left': '0px'
        },
        'fast');
        $('#form_hold').wait(2).then.animate({
            'width': '800px'
        },
        'fast');

        load_data();

        // return the uploader to its original state in case they go back to edit
        $('div.upload-container').show();
    }

    // function to take the user back to the main edit form for editing the current product before saving
    $('#edit_add').click(function()
    {
        // return everything back to visible in case they edit
        $('#add_submit').show();
        $('#add-loader').remove();

        $('#form_hold').css({
            'width': '400px'
        });
        $('#add_image').css('left', '400px');
        $('#preview').animate({
            'left': '400px'
        },
        'fast');
        $('#form_main').animate({
            'left': '0'
        },
        'fast');
        $('#preview-loader,#generate,#info-hold').wait(2).then.remove();
    });

    // function to move past the main form pane to the next
    $('#add_submit').click(function()
    {
        if (validate_form() == true)
        {
            $('#add_submit').after('<img id="add-loader" src="' + global.base + 'assets/_images/ajax-loader.gif"/>').hide();
            $('#form_main').wait(2).then.animate({
                'left': '-400px'
            },
            'fast');
            if ($('#product-shot').length)
            {
                $('#add_image').css({
                    'left': '-400px'
                });
                $('#preview').wait(2).then.animate({
                    'left': '0px'
                },
                'fast');
                $('#form_hold').wait(2).then.animate({
                    'width': '800px'
                },
                'fast');
                load_data();
            }
            else
            {
                $('#add_image').wait(2).then.animate({
                    'left': '0px'
                },
                'fast');
            }
        }
        return false;
    });

    // simple form validation to make sure at least the product number and description are filled out
    function validate_form()
    {
        var partID = $('#part_no').val();
        if ((partID == null) || (partID == '')) {
            alert(opts.part_msg);
            $('#part_no').focus();
            return false;
        }
        var descriptionID = $('#description').val();
        if ((descriptionID == null) || (descriptionID == '')) {
            alert(opts.description_msg);
            $('#description').focus();
            return false;
        }
        return true;
    }

    // load all the data we need from the form pane into the preview pane
    function load_data()
    {
        // assign form data to variables
        part_no = $('#part_no').val();
        cat_name = translate_cat($('#cat_name').val());
        description = $('#description').val();
        price = $('#price').val() > 0 ? $('#price').val() : 0;
        shipping = $('#shipping').val() > 0 ? $('#shipping').val() : 0;
        cat_id = $('#cat_name').val();

        $('#preview h2').after('<div id="info-hold"><p>Part: ' + part_no + '</p><p>Category: ' + cat_name + '</p><p>Description: ' + description + '</p><p>Price: $' + price + '</p><p>Shipping: $' + shipping + '</p></div>');

        // if they confirm the edits - then throw the data to the database via ajax
        $('#confirm_add_product,#confirm_edit_product').click(function() {
            // put the name of the image into the post array
            var img_name = $('input#img_name:hidden').val();
            // use the clicked button's value to determine saving a new product or editing a new one
            var action = $(this).val();
            // determine the proper url to send
            if (action == 'edit')
            var url = 'admin/' + action + '_product/' + $('#id').val();
            else
            var url = 'admin/' + action + '_product'
            $('#add_but_hold').html('<img id="preview-loader" src="' + global.base + 'assets/_images/ajax-loader.gif"/>');
            $.post(global.base + url, {
                part_no: part_no,
                cat_id: cat_id,
                description: description,
                price: price,
                shipping: shipping,
                img_name: img_name
            },
            function(data) {
                $('#add_but_hold').wait(2).then.html('<h2 class="response">' + data + '</h2>');
                setTimeout(function() {
                    window.location = global.base + 'admin/product_list';
                },
                3500);
            });
        });
    }

    // simple switch to pull the right category name from the cat number
    function translate_cat(category)
    {
        switch (category)
        {
        case '1':
            return 'Accessories';
            break;
        case '2':
            return 'Electric Dispensing';
            break;
        case '3':
            return 'Pneumatic Dispensing';
            break;
        default:
            return;
        }
    }

    // if we are editing a product, let's load the functions we need for it
    if ($('#confirm_edit_product').length)
    {
        edit_load();

        // set panes to show product preview
        $('#add_image').css({
            'left':
            '-400px'
        });
        $('#form_main').wait(1).then.animate({
            'left':
            '-400px'
        },
        'fast');
        $('#preview').wait(1).then.animate({
            'left': '0px'
        },
        'fast');
        $('#form_hold').wait(1).then.animate({
            'width': '800px'
        },
        'fast');

        load_data();
    }

}

