
// ECMAScript coding: UTF-8
/**
 * @file src/resources/create.js
 */

var yg_gameEditor = {
    currentXml: '',
    currentWidth: -1,
    currentHeight: -1,

    // Template
    currentTemplateId: -1,
    currentTemplate: null,

    // Skin
    currentSkin: -1,

    gameName: null,

    // Used to know if a confirmation message must be displayed when changing template
    hasChanged: false,

    // Game creation tool
    creationToolReady: false,

    // Snapshot container
    snapshotContainerReady: false,

    // This index is used for making sure we're receiving the "right" ready notification from
    // flash animations.
    rdyIdx: 0,

    // Image list
    useImageLibrary: true,
    hasImage: false,
    hasUserLibrary: false, // true if user is logged.
    libImages: new Array(), // These are images used in user's library
    libImagesIndex: 0,

    // User status
    anonymous: true,
    // New game = false, existing game = true
    existingGame: false,

    backToSaveStep1: function()
    {
        $('creation_gameCreationContainer').show();
        $('creation_gameSaveContainer').hide();

        // Remove the snapshot container
        yg_gameEditor.snapshotContainerDiv.innerHTML = '';

        //Remove content of block_saveStatusDuringAuth
        $('block_saveStatusDuringAuth').innerHTML = '';
    },
    goToSaveStep2: function()
    {
        this.onTitleUpdate();

        if (typeof(urchinTracker) == 'function')
        {
            urchinTracker('/urchin/create_save_button');
        }

        if (typeof(tmp = this.getCT().ctCanSave()) != 'string')
        {
            $('block_saveStatusBeforeAuth').update('Cannot save because something bad happened').addOnlyClassName('error');
            return;
        }
        else if (tmp != 'ok')
        {
            if (tmp == 'no image')
            {
                $('block_saveStatusBeforeAuth').update('Cannot save because your game has no image').addOnlyClassName('error');
            }
            else
            {
                $('block_saveStatusBeforeAuth').update('An unexpected error occured; your game can\'t be saved').addOnlyClassName('error');
            }
            return;
        }

        // Fill-in the xml
        this.currentXml = this.getCT().ctGetData();
        debug('XML received from CT: ['+this.currentXml+']');

        if (this.useImageLibrary)
        {
            // Update and save user library.
            imageResources = this.getCT().ctGetImageResources();
            this.addXmlLibraryItems(imageResources);
        }

        // We're done, now swap the divs.
        $('creation_gameCreationContainer').hide();
        $('creation_gameSaveContainer').show();

        // Then, create the snapshot container
        tmp = '/create/sc/sc.swf?rdyidx='+yg_gameEditor.rdyIdx+'&template='+yg_gameEditor.currentTemplateId;
        debug('Loading SC file ['+tmp+']');

        yg_gameEditor.snapshotContainerDiv.innerHTML = '&nbsp;' + makeFlashObject({
            id: 'create_snapshotContainer_flashObj',
            swf: '/create/sc/sc.swf',
            flashvars: 'rdyidx='+yg_gameEditor.rdyIdx+'&template='+yg_gameEditor.currentTemplateId,
            width: 1,
            height: 1,
            internal: true
        });
        if ($('block_signupLogin') == null)
        {
            yg_gameEditor.save();
            //return;
        }
        else
        {
            if ($('signin_and_save') == null)
            {
                $('block_signinStatus').insert({ after: '<input type="submit" id="signin_and_save" onclick="yg_gameEditor.saveAfterSignIn();" class="buttons" style="margin-left: 100px" value="log in" />' });
                $('block_signupStatus').insert({ after: '<input type="submit" id="signup_and_save" onclick="yg_gameEditor.saveAfterSignUp();" class="buttons" style="margin-left: 150px" value="sign up" />' });
                $('create_saveGame').insert({ after: '<p><a href="javascript:void(0);" onclick="yg_gameEditor.save(true);" style="margin-left: 15px; font-size: 15px">skip sign up</a></p>' });
            }
        }

    },
    saveFromFlash: function()
    {
        setTimeout('yg_gameEditor.goToSaveStep2()', 500);
    },
    enableSave: function(enable)
    {
        var btn = $('create_saveGame_button');
        if (typeof(this.saveImageButtonSrc) == 'undefined')
        {
            this.saveImageButtonSrc = btn.src;
        }

        if ((enable && (!this.useUserLibrary || this.hasImage)) || this.existingGame)
        {
            btn.src = this.saveImageButtonSrc;
            btn.enable();
        }
        else
        {
            // Save the original image src to re-use it when reactivate the save button
            btn.src = '/resources/save_and_play_disabled.gif';
            btn.disable();
        }
    },
    getCT: function()
    {
        if (!this.creationToolReady)
            return null;

        if (navigator.appName.indexOf('Microsoft') != -1)
        {
            return window['create_creationTool_flashObj'];
        }
        else
        {
            return document['create_creationTool_flashObj'];
        }
    },
    getSC: function()
    {
        if (!this.snapshotContainerReady)
            return null;

        if (navigator.appName.indexOf('Microsoft') != -1)
        {
            return window['create_snapshotContainer_flashObj'];
        }
        else
        {
            return document['create_snapshotContainer_flashObj'];
        }
    },
    initialize: function(gameId, s3url, flsync)
    {
        this.gameId = gameId;
        this.s3url = s3url;
        this.flsync = flsync;

        this.creationToolDiv        = $('create_step2FlashPreview');
        this.snapshotContainerDiv   = $('create_snapshotContainer_flash');
        this.existingGame = ($('create_saveGame_edit').value == 'true');
    },
    saveAfterSignIn: function() {
        if ($('block_signinLogin').value != '' ||
                 $('block_signinPassword').value != '')
        {
            this.anonymous = false;
            signin(null, yg_gameEditor.saveRegistered);
            return;
        }
    },
    saveAfterSignUp: function() {
        if ($('block_signupLogin').value != '' ||
                 $('block_signupPassword').value != '')
        {
            this.anonymous = false;
            signup(null, yg_gameEditor.saveRegistered);
            return;
        }
    },
    save: function(anonymous)
    {
        if (typeof(urchinTracker) == 'function')
        {
            urchinTracker('/urchin/create_login_signup_or_skip');
        }

        var tmp, name;

        // Check our fields (name & description) prior to trying to authenticate user
        if (!(tmp = $('create_gameInfo_name')) || (yg_gameEditor.gameName = tmp.value.strip()).length == 0) {
            yg_gameEditor.gameName = '';
        }

        // Then, login or register user
        if ($('block_signupLogin') == null)
        {
            // There is no signup / signin form
            this.anonymous = false;
            yg_gameEditor.saveRegistered();
            return;
        }
        else if (anonymous === true)
        {
            this.anonymous = true;
            if (confirmSkipSignUp() == true)
                {
                    yg_gameEditor.saveRegistered();
                    return;
                }
            else {
                return;
            }
        }

        $('block_saveStatusDuringAuth').update('You must either login, register or choose to stay anonymous to save this game').addOnlyClassName('error');
    },
    saveRegistered: function()
    {
        // If user is logged, merge its library (if needed).
        if (yg_gameEditor.useImageLibrary && yg_gameEditor.anonymous == false)
            yg_gameEditor.mergeUserLibrary();

        // Create ajax request
        var args = {
            game: $('create_saveGame_code').value,
            name: yg_gameEditor.gameName,
            description: $('create_gameInfo_description').value.strip(),
            tags: $('create_gameInfo_tags').value.strip(),
            template: yg_gameEditor.currentTemplateId,
            width: yg_gameEditor.currentWidth,
            height: yg_gameEditor.currentHeight,
            skin: yg_gameEditor.currentSkin,
            xml: yg_gameEditor.currentXml,
            anonymous: yg_gameEditor.anonymous,
            edit: yg_gameEditor.existingGame
        }

        // Send the request
        postRequest = new yRemote();

        // Display throbber
        throbber = new yg_throbber();
        throbber.show('block_saveStatusDuringAuth_throbber', null, true);

        postRequest.onLoad = function(status, data)
        {
            debug('postRequest onLoad');
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success)
                {
                    // Run first request in a couple of seconds
                    setTimeout('runSaveRequest()', 1000);
                }
                else
                {
                    if (throbber)
                        throbber.hide();
                    var backLinkTitle = 'Back to previous step';
                    var backLink = new Element('a', { href: 'javascript:yg_gameEditor.backToSaveStep1()', title: backLinkTitle }).update(backLinkTitle);
                    var backDiv = new Element('div').update(backLink);
                    $('block_saveStatusDuringAuth').appendChild(backDiv);
                }
            }
        }

        postRequest.post('/services/creation/saveGame.php', args);

        // Fire a global timeout...
        setTimeout('failedSaving()', 120000); // 120 seconds (2 minutes)

        // That's all folks!
        return true;
    },
    setEditedGameInfo: function(template, name, skin, width, height, ctWidth, ctHeight, ct)
    {
        getXmlRequest = new yRemote();

        getXmlRequest.onLoad = function(status, data)
        {
            debug('getXmlRequest onLoad');
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                xml = data;
                yg_gameEditor.selectTemplate(template, name, skin, xml, width, height, ctWidth, ctHeight, ct);
            }
        }
        debug('sending getXmlRequest');
        getXmlRequest.getRawData('/services/creation/getXml.php?gameCode='+yg_gameEditor.gameId);

    },
    selectAnotherTemplate: function(template, name)
    {
        var redirect;

        if (template == this.currentTemplateId)
            return;

        this.hasChanged |= this.hasImage || ($('create_gameInfo_description').value != '') || ($('create_gameInfo_tags').value != '');

        if (this.hasChanged == true)
            redirect = confirm('If you select another template, your modifications will not be saved. Are you sure?');
        else
            redirect = true;

        if (redirect == true)
            window.location = '' + template + name;
    },
    selectTemplate: function(template, name, skin, xml, width, height, ctWidth, ctHeight, ct)
    {
        var tmp;

        if (typeof(urchinTracker) == 'function')
        {
            urchinTracker('/urchin/create_select_template');
        }

        if (this.currentTemplateId == template)
            return;

        // If game template is not same version, we must reload page
        if ((this.currentTemplateId != -1) &&
            (((this.currentTemplateId > 100) && (template < 100)) ||
             ((this.currentTemplateId < 60) && (template > 60)) ||
             ((this.currentTemplateId > 60) && (this.currentTemplateId < 98) && ((template < 60) || (template > 98)))))
        {
            var answer = confirm('You will be redirected to another page for this game. Your game will not be saved. Are you sure?');
            if (answer == true)
                window.location = 'http://www.pictogame.com/create/' + template + name;
            return;
        }

        this.currentTemplateId = template;

        // Inherits xml from previous template
        if (xml !== null)
            this.currentXml = xml;
        else if (tmp = this.getCT())
            this.currentXml = tmp.ctGetData();

        this.currentWidth = width;
        this.currentHeight = height;

        this.currentSkin = skin;

        // Okay, the template changed.
        // This means we have to (re)load the game creation tool

        this.rdyIdx++;

        if (this.currentCT != ct)
        {
            this.currentCT = ct;
            this.creationToolReady = false;
        }

        // Disable the save buttons until game creation tool is loaded and have received its data
        this.enableSave(false);

        // Okay, the above code was failing badly with IE 7. It seems that the hoster *must* be part of the initial DOM

        tmp = '/create/ct/ct'+ct+'.swf';
        tmp += ' & flashvars = "rdyidx='+this.rdyIdx+'&synchro='+this.flsync+'&s3url='+encodeURIComponent(this.s3url)+'"';

        debug('Loading CT file ['+tmp+']');

        if (!this.creationToolReady)
        {
            this.creationToolDiv.update(makeFlashObject({
                id: 'create_creationTool_flashObj',
                swf: '/create/ct/ct' + ct + '.swf',
                flashvars: 'rdyidx='+this.rdyIdx+'&synchro='+this.flsync+'&s3url='+encodeURIComponent(this.s3url),
                width: ctWidth,
                height: ctHeight,
                internal: true
            }));
        }
    },
    addXmlLibraryItems: function(xmlArray)
    {
        for (i = 0; i < xmlArray.length; i++)
        {
            var xmlResource = Xparse(xmlArray[i]);
            if (xmlResource.contents == null)
                return;
            this.addLibraryItem(xmlResource.contents[0]);
        }
        this.saveUserLibrary();
    },
    addUrlLibraryItem: function(url)
    {
        escapedUrl = url.replace('<', '%3C');
        escapedUrl = escapedUrl.replace('"', '%22');
        escapedUrl = escapedUrl.replace('>', '%3E');

        var xml = '<IMAGE><FILE URL="'+escapedUrl+'" /></IMAGE>';

        var xmlResource = Xparse(xml);
        if (xmlResource.contents == null)
            return;
        itemIndex = this.addLibraryItem(xmlResource.contents[0]);
        this.showUserLibrary(itemIndex);
        this.selectLibraryItem(itemIndex);
        this.saveUserLibrary();
    },
    addLibraryItem: function(xmlResource, append)
    {
        if (!this.existingGame)
        {
            $('create_step1Lib_msg').innerHTML = '';
            $('create_step1Lib_msg').addOnlyClassName('status');
        }

        if (append == null)
            append = false;

        var resourceItem;
        for (var j = 0; j < xmlResource.contents.length; j++)
        {
            resourceItem = xmlResource.contents[j];
            if (resourceItem.type == 'element')
            {
                if ((resourceItem.name == 'PANZOOMROTATE') || (resourceItem.name == 'FILE'))
                {
                    // We found the new resource id.
                    var resId = resourceItem.attributes['URL'];
                    var newItem = {'url': resId, 'content': xmlResource.innerStr};

                    // First, search image url among library
                    var numLibraryItems = this.libImages.length;
                    for (var i = 0; i < numLibraryItems; i++)
                    {
                        if (this.libImages[i].url == resId)
                        {
                            if (!append)
                            {
                                if (resourceItem.name != 'FILE')
                                {
                                    // Update item
                                    this.libImages[i] = newItem;
                                }
                            }
                            return i;
                        }
                    }

                    if (append)
                    {
                        // Enqueue new item
                        this.libImages.push(newItem);
                        return this.libImages.length - 1;
                    }
                    else
                    {
                        // Remove oldest library item if there are too much images.
                        var limit = 10;
                        if (numLibraryItems >= limit - 1)
                        {
                            if (!this.existingGame)
                            {
                                $('create_step1Lib_msg').innerHTML = 'Your library is full, oldest image has been removed';
                                $('create_step1_id').setStyle({height: '190px'});
                                $('create_step1Lib_msg').addOnlyClassName('error');
                            }
                            this.libImages.splice(limit - 2, numLibraryItems - limit + 1);
                        }

                        // Then insert new item at first position
                        this.libImages.splice(0, 0, newItem);
                        return 0;
                    }
                }
            }
        }
    },
    removeLibraryItem: function(index)
    {
        if ((index == null) || (index < 0) || (index >= this.libImages.length))
            return;

        ct = this.getCT();
        if (ct != null && window.confirm('Are you sure you want to delete this image? You will not be able to use it later'))
        {
            this.libImages.splice(index,1);
            this.saveUserLibrary();
            if (this.libImages.length == 0)
            {
                new Effect.Fade('create_step1Lib_imgList_title');
                new Effect.Fade('create_step1Lib_imgList_item'+index);
            }
            else
                yg_gameEditor.showUserLibrary(index);
        }
    },
    selectLibraryItem: function(index)
    {
        if ((index == null) || (index < 0) || (index >= this.libImages.length))
            return;

        ct = this.getCT();
        if (ct != null)
        {
            xmlContent = this.libImages[index].content;
            if (xmlContent.substring(0, 12) != '<IMAGE><FILE')
            {
                ct.ctAddImageResource(xmlContent);
            }
            else
            {
                ct.ctAddImage(this.libImages[index].url);
            }

            this.hasImage = true;
            this.enableSave(true);
            new Effect.ScrollTo('create_step2FlashPreview', {offset: -5});
        }
    },
    loadUserLibrary: function(xml)
    {
        xmlLib = Xparse(xml);
        if (xmlLib.contents == null)
            return;
        resourcesList = xmlLib.contents;
        for (var i = 0; i < resourcesList.length; i++)
        {
            resource = resourcesList[i];
            if (resource.type == 'element' && resource.name == 'IMAGE')
            {
                this.addLibraryItem(resource, true);
            }
        }
        this.hasUserLibrary = true;
        this.showUserLibrary();
    },
    shiftLeftUserLibrary: function(index)
    {
        this.showUserLibrary(this.libImagesIndex - 1);
    },
    shiftRightUserLibrary: function()
    {
        this.showUserLibrary(this.libImagesIndex + 1);
    },
    showUserLibrary: function(index)
    {
        if ((this.existingGame == true) || (this.libImages.length == 0))
            return;

        if (index != null)
        {
            this.libImagesIndex = index;
            if (this.libImagesIndex > this.libImages.length - 5)
                this.libImagesIndex = this.libImages.length - 5;
            if (this.libImagesIndex < 0)
                this.libImagesIndex = 0;
        }

        libContent = '<h4 id="create_step1Lib_imgList_title">... or from your personal library</h4>';

        var maxIndex = this.libImagesIndex + 5;
        if (maxIndex > this.libImages.length)
            maxIndex = this.libImages.length;

        if (this.libImagesIndex > 0)
            libContent += '<span class="pager" style="float: left;"><a href="javascript:void(0);" onclick="yg_gameEditor.shiftLeftUserLibrary(); return false;">' +
                          '&lt;' +
                          '</a></span>' + "\n";

        if (maxIndex < this.libImages.length)
            libContent += '<span class="pager" style="float: left;"><a href="javascript:void(0);" onclick="yg_gameEditor.shiftRightUserLibrary(); return false;">' +
                          '&gt;' +
                          '</a></span>' + "\n";

        libContent += '<div id="create_step1Lib_imgList">';
        libContent += '<table>';
        libContent += '<tr>';

        for (i = this.libImagesIndex; i < maxIndex; i++)
        {
            libContent += '<td id="create_step1Lib_imgList_item'+i+'" width="40" align="center">' +
                          '<a title="Select this picture" href="javascript:void(0);" onclick="yg_gameEditor.selectLibraryItem('+i+'); return false;">' +
                          '<img class="create_step1Lib_image" src="'+ this.libImages[i].url +'" style="height: 40px;" onload="yg_gameEditor.resizeUserLibraryImage(this);" />' +
                          '</a>' +
                          '<br />' +
                          '<a title="Remove from your library" href="javascript:void(0)" onclick="yg_gameEditor.removeLibraryItem('+i+'); return false;" style="padding-top: 2px;">' +
                          '<img src="/resources/game_delete.gif" alt="" />' +
                          '</a>' +
                          '</td>' + "\n";
        }
        libContent += '</tr>';
        libContent += '</table>';
        libContent += '</div>';



        libContent += '<div class="spacer">&nbsp;</div>';
        $('create_step1Lib').innerHTML = libContent;

    },
    resizeUserLibraryImage: function(img)
    {
        if (img.width > 80)
            img.setStyle({ width: '80px', height: '' });
    },
    saveUserLibrary: function(force)
    {
        if (force == null)
            force = false;
        if ((this.hasUserLibrary == false) && (force == false))
            return; // We can't save because user isn't logged in.
        var xmlResult = '';
        for (i = 0; i < this.libImages.length; i++)
        {
            xmlResult += this.libImages[i].content + "\n";
        }

        // Send ajax request
        saveLibRequest = new yRemote();
        saveLibRequest.onLoad = function(status, data)
        {
            debug('saveLibRequest onLoad');
            if (status == 200 && data !== null)
            {
                debug('library saved');
                yg_gameEditor.hasUserLibrary = true;
            }
        }
        if (xmlResult != '')
        {
            saveLibRequest.post('/services/library/saveUserLib.php', {xml: xmlResult});
        }
    },
    mergeUserLibrary: function()
    {
        if (this.hasUserLibrary == true)
            return; // No need to merge if user already have library.

        // Get user library.
        getLibRequest = new yRemote();
        getLibRequest.onLoad = function(status, data)
        {
            debug('getLibRequest onLoad');
            if (status == 200 && data !== null)
            {
                // Got definitive response (success or failure)
                if (data.success && data.xml != '')
                {
                    // Merge library
                    yg_gameEditor.loadUserLibrary(data.xml);
                }
                // And save it
                setTimeout('yg_gameEditor.saveUserLibrary(true)', 50);
            }
        }
        getLibRequest.post('/services/library/getUserLib.php', {});

    },
    onTitleUpdate: function()    // Check user library save status prior to check game save status
    {
        ct = this.getCT();
        if (ct != null)
        {
            if (typeof(ct.ctSetTitle) != 'undefined')
            {
                ct.ctSetTitle($('create_gameInfo_name').value + '.'); // Leave the trailing dot (flash bug)!
            }
        }
    },
    checkTitleEdited: function(defaultName)
    {
        if ($('create_gameInfo_name').value != defaultName)
            this.hasChanged = true;
    },
    setCreationToolReady: function(rdyIdx)
    {
        if (rdyIdx != this.rdyIdx)
            return;

        debug('setCreationToolReady('+rdyIdx+')');

        this.creationToolReady = true;
        ct = this.getCT();
        if (ct != null)
        {
            var xml = yg_gameEditor.currentXml;

            debug('XML sent to creation tool ['+xml+']');
            ct.ctSetData(xml);
        }

        this.onTitleUpdate();
        this.enableSave(true);
    },
    setSnapshotContainerReady: function(rdyIdx)
    {
        if (rdyIdx != this.rdyIdx)
            return;

        debug('setSnapshotContainerReady('+rdyIdx+')');

        this.snapshotContainerReady = true;

        // Xml, if any, should be sent to the snapshot container at this moment.
        debug('XML: ['+yg_gameEditor.currentXml+']');
        this.getSC().scSetData(yg_gameEditor.currentXml);
    }
}

/***********************************************************************/
/* Save functions */

function runSaveRequest()
{
    // Check user library save status prior to check game save status
    if (yg_gameEditor.useUserLibrary && !yg_gameEditor.hasUserLibrary && !yg_gameEditor.anonymous)
    {
        setTimeout('runSaveRequest()', 2000);
        return;
    }

    saveRequest = new yRemote();
    saveRequest.onTimeout = function()
    {
        // Reschedule again!
        setTimeout('runSaveRequest()', 1000);
    }

    saveRequest.onLoad = function(status, data)
    {
        debug('saveRequest.onLoad('+status+')');

        if (status == 200 && data !== null)
        {
            // Got response (success or failure)
            if (data.success)
            {
                if (data.saved)
                {
                    if (throbber)
                        throbber.hide();
                    debug('Game was saved');
                    if (typeof(urchinTracker) == 'function')
                    {
                        urchinTracker('/urchin/create_game_save_ok');
                    }
                    setTimeout("redirect('/share.php?game=' + $('create_saveGame_code').value + '&alpha-v=1')", 100);
                    return;
                }
            }
            else
            {
                debug('Got error');
                return;
            }
        }

        // Otherwise, reschedule
        debug('Rescheduling in two seconds');
        setTimeout('runSaveRequest()', 1500);
    }

    debug('Scheduling request...');
    saveRequest.get('/services/creation/getSaveStatus.php', 4); // 4 seconds timeout
}

function failedSaving()
{
    debug('failed saving!');
}

/****************************************************************************************************************************/
/* Wrappers for callbacks from flash movies */

/* These are called from the creation tool */

function ctReady(rdyidx)
{
    debug('Creation tool is ready ('+rdyidx+')');
    setTimeout('yg_gameEditor.setCreationToolReady('+rdyidx+')', 50);
}

/* Callbacks from snapshot container */
function scReady(rdyidx)
{
    debug('Snapshot tool is ready ('+rdyidx+')');
    setTimeout('yg_gameEditor.setSnapshotContainerReady('+rdyidx+')', 50);
}

/* This is called from image uploader */
function ilibSetImage(imgurl)
{
    debug('received ilibSetImage call ('+imgurl+')');
    setTimeout('yg_gameEditor.addUrlLibraryItem("'+imgurl+'")', 50);
}

/* Message Box Example */

function confirmSkipSignUp()
{
    var answer;
    answer = confirm('Are you sure? You won\'t be able to edit this game later.');
    return answer;
}
