// For any third party dependencies, like jQuery, place them in the lib folder.

// Configure loading modules from the lib directory,
// except for 'app' ones, which are in a sibling
// directory.
var APP = {};
var TOOLS = "enhance,effects,orientation,crop,warmth,brightness,draw,text";/*Removed tools: Resize, Frames, Stickers, Focus, Saturation, Contrast, Sharpness, Redeye, Whiten, Blemish, Splash*/
var langCode = navigator.mozL10n.language.code;
var DEFAULTDATE = "ddd MMM dd HH:mm:ss yyyy";
var FILEFORMAT = 'yyyyddMM_hhmmss';
if(langCode === "pt-BR"){langCode = "pt_BR"}
    
if(langCode !== 'pt_BR' && langCode !== 'es' && langCode !== 'fr'){
    langCode = 'en';
}
 var options = { 
                    appVersion: "1.1",
                    polling: 10000,
                    uploadTimeout: 60000,
                    sessionTimeoutSeconds: 30,
                    storage: 100000,
                    logger: true
                 };

requirejs.config({
    baseUrl: 'js/lib',

    // Map jquery to zepto
    map: {
        '*': {
            'jquery': 'zepto'
        }
    },

    paths: {
        app: '../app',
        models: '../app/models',
        collections: '../app/collections',
        views: '../app/views',
        templates: '../app/templates',
        db: '../app/db'
    }
});

requirejs(['views/ViewSplash','collections/list','localytics', 'zepto'], function (ViewSplash,List, Localytics, $) {
    //localStorage.clear();
    var list = new List();
    splashView = new ViewSplash({
        collection:list
    });
    splashView.render();
    APP.viewSplash = splashView; 
    localyticsSession = LocalyticsSession("2942ba90927b22dc2433f48-d04e4616-8da9-11e3-1a55-004a77f8b47f", options);
    localyticsSession.open();
});

var toollist = localStorage.getItem('selectedTools');

if(toollist === null){
    toollist = TOOLS;         
}

/* var vibrateInterval;

// Starts vibration at passed in level
function startVibrate() {
    navigator.vibrate(100);
	//stopVibrate();
}

// Stops vibration
function stopVibrate() {
    // Clear interval and stop persistent vibrating 
    if(vibrateInterval) clearInterval(vibrateInterval);
    navigator.vibrate(0);
}

// Start persistent vibration at given duration and interval
// Assumes a number value is given
function startPeristentVibrate() {
    vibrateInterval = setInterval(function() {
        startVibrate();
    }, 100);
} */

//var hasPurchased = false; // you can change this whatever you like. maybe use localStorage to persist this value (when the user purchases and close editor)

/*//AV.build['feather_stickerURL'] = AV.build["feather_baseURL"] + '/images/feather_stickers/';
if (hasPurchased){
    TOOLS = "enhance,effects,stickers,orientation,focus,resize,crop,warmth,brightness,contrast,saturation,sharpness,colorsplash,draw,text,redeye,whiten,blemish";
}
AV.Events.on('tool:init',function(tool){
    if (hasPurchased && tool === 'effects') {

        Aviary_ReloadWithPurchasedAssets();
    }
});*/
var featherEditor = new Aviary.Feather({
    isMobile: true,
    // forceGL: true,
    theme: 'dark', // Check out our new 'light' and 'dark' themes!
    tools: TOOLS,
    maxSize : '400',
    language : langCode,	 
    onLoad: function(){
        var photoeditor = $('#picEdit').html();
		var exitEditor = $('#exitEditor').html();
        var avpw_controls =  $('#avpw_controls');
        var len;
        avpw_controls.append("<div id='bck' class='avpw_button left'></div>");    
        $('#avpw_all_effects').html('');
        $('#avpw_footer').append('<div id="avpw_title" data-l10n-id="PhotoEditor" class="left"><h1>'+ photoeditor +'</h1></div>');
        $('#avpw_canvas_embed').append('<input type="text" id="focusField" style="width:0px;height:0px;background-color:#000;border:0px;color:#000;padding:1px;margin-left:-5px;position:absolute" />');
        avpw_controls.append('<div id="separatorHead" class="right"></div><div id="editHeader"></div>');
        avpw_controls.on("click", function(event){
			len = $('.avpw_textwithfont_entry').length;
            if(event.target.nodeName !== "INPUT" && event.target.nodeName != "TEXTAREA"){
              
                $('#avpw_resize_width').blur();
                $('#avpw_resize_height').blur();
            }
        });
		
		
        $('#bck').click(function(){
			var backToHome = confirm(exitEditor);
            if (backToHome) {
				$('#view-imageDetails').hide();
				$('#homeScreen').css('visibility','visible');
				featherEditor.close();
				$('#avpw_holder').hide();
			}
        });
		
        $('#avpw_save_button').on("click", function(event){
		/* var len = $('#focusField').length;
			alert("len:"+len); */
			
			$('#view-imageDetails').hide();
			if($('#avpw_apply_container').is(':visible')){
				if(len >= 1){
					$('#focusField').focus().trigger('blur');
				}
			}
            if(!$('#avpw_apply_container').is(':visible')){
                //save Image
                saveImage();
            }
            return true;
        });		
    },
	onReady: function(){
         
        $('div#avpw_canvas_embed.avpw_canvas_background').append('<input type="text" id="focusField" style="width:0px;height:0px;background-color:#000;border:0px;color:#000;padding:1px;margin-left:-5px;position:absolute" />');

		
		$(".avpw_slider_container").on("touchstart", function(){
			if(localStorage.getItem("vibration") == "true"){
                 navigator.vibrate(100);
            }
		}); 
		
		 $(".avpw_slider_handle").on("touchstart", function(){
			if(localStorage.getItem("vibration") == "true"){
                 navigator.vibrate(100);
            }
		});
		 /*$(".avpw_slider_positioned").on("touchstart", function(){
			if(localStorage.getItem("vibration") == "true"){
                 navigator.vibrate(100);
            }
		}); 
		$(".avpw_slider_positioned_inner").on("touchstart", function(){
			if(localStorage.getItem("vibration") == "true"){
                navigator.vibrate(100);
            }
        }); */
		
		 
		  $(".avpw_slider_bookend avpw_slider_bookend_right avpw_slider_label").on("touchstart", function(){
			if(localStorage.getItem("vibration") == "true"){
                navigator.vibrate(100);
            }
        });
			$(".avpw_slider_bookend avpw_slider_bookend_left avpw_slider_label").on("touchstart", function(){
			if(localStorage.getItem("vibration") == "true"){
                navigator.vibrate(100);
            }
        });
		
       /*  $(".avpw_slider_handle").on("touchend", function(){                
				navigator.vibrate(0);          
        }); */
		
       
        
		
		/* $(".avpw_slider_positioned").on("touchend", function(){
            navigator.vibrate(0);
        }); */
        
      
       /*  $("avpw_slider_bookend avpw_slider_bookend_right avpw_slider_label").on("touchend", function(){
            navigator.vibrate(0);
        });
		 */
	
        
        /* $("avpw_slider_bookend avpw_slider_bookend_left avpw_slider_label").on("touchend", function(){
            navigator.vibrate(0);
        }); */
		
		
		
		/* $("avpw_slider_positioned_inner").on("touchend", function(){
            navigator.vibrate(0);
        }); */
	},

    onSave: function(imageID, newURL) {
        var img = document.getElementById(imageID);
        img.src = newURL; 
			
    },
    onSaveButtonClicked: function(imageID){
        return false;
    },    
    onError: function(errorObj) {
        alert(errorObj.message);
    }
});


/*
var Aviary_ReloadWithPurchasedAssets = function(){
    
    var _customAssetsByType = {
        /*'EFFECT': [
            /*
            Uncomment if you'd like to 
            { // prexisting pack
                "needsPurchase": false,
                "assetId": "default_effects",
                "assetType": "effect",
                "displayName": "Default",
                "resourceUrl": "js/proclist_default_effects.js"
            },
            { // prexisting pack
                "needsPurchase": false,
                "assetId": "original_effects",
                "assetType": "effect",
                "displayName": "Original",
                "resourceUrl": "js/proclist_original_effects.js"
            },*/

            // one of our best selling packs!
            /*{
                "customPack": true, // Should have special packId
                "needsPurchase": false,
                "assetId": "wanderlust_effects",
                "assetType": "effect",
                "displayName": "Wanderlust",

                // NOTE: copy that file to your relative path (i.e. /aviary/..)
                "resourceUrl": "http://localhost/tester/proclist_wanderlust.js"
            }
        ]
        , 'STICKER': [
            { // preexisting stickers
                "needsPurchase": false,
                "assetId": "original_stickers",
                "assetType": "sticker",
                "displayName": "Original",
                "resourceUrl": AV.build["feather_baseURL"]+"images/feather_stickers/stickers_original_stickers.js"
            },

            { // custom stickers, follow this format:
                "needsPurchase": false,
                "assetId": "halloween_stickers",
                "assetType": "sticker",
                "displayName": "Halloween",
                //
                // This is just an example URL,
                // You can copy the file to a relative path: /js/stickers_halloween.js
                //
                "resourceUrl": "http://feather.aviary.com/3.1.0.246/js/stickers_halloween.js"
            }

        ]        
    }

    var _getCustomAssetsByType = function(type){
        return _customAssetsByType[type];
    };

    // helper include
    var _fixAssetURL = function(asset) {
        var url = asset.resourceUrl;
        if (url) {
            // check if it is relative
            if (url.indexOf('http') === -1) {
                url = AV.build['feather_baseURL'] + url;
            }
            asset.resourceUrl = url;
        }
    };

    var oldGetAssetsFunc = AV.controlsWidgetInstance.assetManager.getAssets;
    AV.controlsWidgetInstance.assetManager.getAssets = function(type, callback){
        var assets = _getCustomAssetsByType(type);
        if (assets && assets.length) {

            if (type == 'EFFECT') {
                var deferredCount = 0,
                    loadedCount = 0;

                for (var i = 0; i < assets.length; i++) {
                    _fixAssetURL(assets[i]);
                    if (assets[i].customPack) {
                        var $codeLoad = avpw$.Deferred();
                        
                        deferredCount++;

                        AV.paintWidgetInstance.filterManager.loadPack(
                            assets[i].assetId,
                            assets[i].resourceUrl,
                            function() {
                                $codeLoad.resolve();
                            }
                        );
                        $codeLoad.done(function(){
                            loadedCount++;
                            if (deferredCount === loadedCount) {
                                callback.apply(this, [assets]);
                            }
                        });
                   }
                }
            } else {
                callback.apply(this, [assets]);
            }
        } else {
            return oldGetAssetsFunc.apply(this, arguments);
        }
    };
};*/

function launchEditor(id, src) {
    featherEditor.launch({
        image: id,
        url: src
    });
    return false;
}

function saveImage(){
    
    localyticsSession.tagEvent("Save this photo.");
    localyticsSession.upload();
    
    var errorMsg = $('#errorMsg').html();
    featherEditor.getImageData(function(dataURL) {
        var newImg = document.createElement("img");
        newImg.src = dataURL;      

        // Save image on the device 
        var data = atob( dataURL.substring( "data:image/png;base64,".length ) ),
        asArray = new Uint8Array(data.length);

        for( var i = 0, len = data.length; i < len; ++i ) {
            asArray[i] = data.charCodeAt(i);    
        }
        fnameFormat = (localStorage.getItem('fnameFormat') != null ) ? localStorage.getItem('fnameFormat') : "yyyyMMdd_hhmmss" ; 

        datetime = $.format.date(new Date(), fnameFormat);

        var outputFolder = (localStorage.getItem('outputFolder') == "" || localStorage.getItem('outputFolder') == null ) ?  "pictures" : localStorage.getItem('outputFolder') ; 

        var sdcard = navigator.getDeviceStorage(outputFolder);

        var file   = new Blob( [ asArray.buffer ], {
            type: "image/png"
        } );

        // store image
        var request = sdcard.addNamed(file, datetime+".png");

        request.onsuccess = function () {
            var name = this.result;
            //console.log('File "' + name + '" successfully wrote on the sdcard storage area');

            APP.viewSplash.addSlide(name,outputFolder);
            featherEditor.close();
            $('#homeScreen').css('visibility','visible');
        }

        // An error typically occur if a file with the same name already exist
        request.onerror = function () {
            alert(errorMsg + this.error.name);
            console.warn('Unable to write the file: ' + this.error);
        }
    });
}
