/*
 * YSCCUP - backing code for uploader/resizer embedded forms
 *
 * JS params:
 *   YSCCUP.mode - upload or resize
 *   YSCCUP.min_height - for cropping, default 60
 *   YSCCUP.min_width  - for cropping, default 90
 *   YSCCUP.random_dir - the randomized directory name for storing the cropped images
 */

var yui = YAHOO.util;
var YSCCUP = new Object();

YSCCUP.initialize = function() {

    // Setup close link
    yui.Event.addListener('close_link', 'click', YSCCUP.closeForm);
    yui.Event.addListener('save_button', 'click', YSCCUP.showLoadingImage);

    // If we're in resize mode, crank up those bits too.
    if (YSCCUP.mode == 'resize') {
        YSCCUP.initializeResize();
    }

};
form.safeInit(YSCCUP.initialize);


/*********************************************************
 *                    Open/Close
 *********************************************************/
YSCCUP.notifyRevealed = function() {
    YSCCUP.recenterImageOnLoad();
    if (YSCCUP.crop != undefined) {
        YSCCUP.buildCropperOnLoad();
    }
};

YSCCUP.closeForm = function(evt) {
    window.location = YSCCUP.storefront_url + 'custom-cover-uploader-closed';
    yui.Event.preventDefault(evt);
    return false;
};

YSCCUP.showLoadingImage = function() {
    yui.Dom.setStyle('loading_img', 'display', 'block');
};

/*********************************************************
 *                      Resizing
 *********************************************************/
YSCCUP.initializeResize = function() {
    // Current aspect ratio is w:h 214:148 ~ 1.4459 = almost 1.5 = 60:90
    YSCCUP.min_height = YSCCUP.min_height ||  60;
    YSCCUP.min_width  = YSCCUP.min_width  ||  90;

    // Setup crop button
    yui.Event.addListener('crop_button', 'click', YSCCUP.cropButtonPressed);

    // Setup upload another button
    yui.Event.addListener('upload_another_button', 'click', YSCCUP.uploadAnotherPressed);

    // Setup recenter-on-load
    yui.Event.addListener('resize_image', 'load', YSCCUP.recenterImageOnLoad);

    // Add cropper after image loads, so initial position is sensible
    var img = yui.Dom.get('resize_image');
    if (img.complete) {
        YSCCUP.buildCropperOnLoad();
    } else {
        yui.Event.addListener('resize_image', 'load', YSCCUP.buildCropperOnLoad);
    }

};
// Setup recenter-on-load
yui.Event.addListener('resize_image', 'load', YSCCUP.recenterImageOnLoad);

// Add cropper after image loads, so initial position is sensible
yui.Event.addListener('resize_image', 'load', YSCCUP.buildCropperOnLoad);

// On crop, fire off an Ajax call to do the cropping.
YSCCUP.cropButtonPressed = function(evt) {
    var coords = YSCCUP.crop.getCropCoords();
    var url = '/yscc-upload/save-crop' +
        '?crop_top='    + coords.top    +
        '&crop_left='   + coords.left   +
        '&crop_height=' + coords.height +
        '&crop_width='  + coords.width  +
        '&random_dir='    + YSCCUP.random_dir;

    var opts = { success: YSCCUP.cropSaved, failure: YSCCUP.cropSaveFailed };

    yui.Dom.get('crop_button').disabled = true;
    yui.Dom.get('upload_another_button').disabled = true;

    yui.Connect.asyncRequest('GET', url, opts);
};

// If the crop save was successful, notify the parent UI of this fact so we can transform the upload page to the preview page.
YSCCUP.cropSaved = function(o) {

    var info = eval('(' +  o.responseText + ')');
    yui.Dom.get('crop_button').disabled = false;
    yui.Dom.get('upload_another_button').disabled = false;

    if (info.success) {
        var url = YSCCUP.storefront_url + 'custom-cover-uploader-closed?';
        url = url + 'preview_url=' + encodeURIComponent(info.preview_url);
        url = url + '&random_dir=' + YSCCUP.random_dir;
        window.location = url;
    } else {
        alert(info.error);
    }
};

// If the crop save failed, alert that fact (and give up?)
YSCCUP.cropSaveFailed = function(o) {
    alert('AJAX failure: \n' + o.statusText);
};

// If the user decides to throw away the uploaded photo, redirect the iframe back to the upload step.
YSCCUP.uploadAnotherPressed = function() {
    var url = '/yscc-upload/upload' +
                  '?random_dir=' + YSCCUP.random_dir +
                  '&mode=upload';

    window.location = url;
};

// Fancy magic to center the crop original in the crop window.
YSCCUP.recenterImageOnLoad = function(evt) {

    // Figure out stage size
    var stage_region = yui.Dom.getRegion('image_stage');
    var image_region = yui.Dom.getRegion('resize_image');

    var stage_width = stage_region.right - stage_region.left;
    var stage_height = stage_region.bottom - stage_region.top;
    var image_width = image_region.right - image_region.left;
    var image_height = image_region.bottom - image_region.top;

    var new_left = stage_region.left + stage_width/2 - image_width/2;
    var new_top  = stage_region.top  + stage_height/2 - image_height/2;

    yui.Dom.setXY('image_centerer', [new_left, new_top], false);

};

// Build the cropper functionality into the page.
YSCCUP.buildCropperOnLoad = function(evt) {
    if (YSCCUP.crop != undefined) { return; }

    var image = yui.Dom.get('resize_image');

    var init_x = image.width/2 - YSCCUP.min_width/2;
    var init_y = image.height/2 - YSCCUP.min_height/2;

    // Setup imagecropper
    var opts = new Object();
    opts.initialXY    = [init_x, init_y];
    opts.initHeight   = YSCCUP.min_height;
    opts.initWidth    = YSCCUP.min_width;
    opts.minHeight    = YSCCUP.min_height;
    opts.minWidth     = YSCCUP.min_width;
    opts.keyTick      = 5;
    opts.shiftKeyTick = 50;
    opts.status       = false;
    opts.ratio        = true;

    YSCCUP.crop = new YAHOO.widget.ImageCropper('resize_image', opts);
};

