/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
 * $Id$
 */

// The FLYFI preferences are saved in local cookies.

// utilities from http://www.quirksmode.org/js/cookies.html

if (typeof(FLYFI) == 'undefined') {
    var FLYFI = function() {};
}


FLYFI.ADD_TARGET_LIBRARY = 'addTarget'; // Key for cookie value that stores last library selected for add.
FLYFI.BIG_VIDEO = "FLYFI_BIG_VIDEO"; // Key for cookie value that shows current video size preference.
FLYFI.IS_PLAYING = 'isPlaying'; // Key for cookie value that says whether a track is playing when the page is unloaded.
FLYFI.LIBRARY_TRACK = 'libraryTrack'; // Key for cookie dict that maps library id to current track id.
FLYFI.WINDOW_MESSAGE = 'winMsg:'; // Prefix for messages to the "other" FlyFi window.
FLYFI.WINDOW_COOKIE = 'FLYFI.windowMsgs'; // Cookie name for inter-window messages.

// NOTE: FLYFI.NOTCOLDSTART is used in server/apps/libraries/views.py
FLYFI.NOTCOLDSTART = 'notCold'; // Key for cookie that inidicates a returning user.

FLYFI.createCookie = function(name,value,days) {
    var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
};

FLYFI.readCookie = function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
    var l = ca.length;
	for(var i=0;i < l;i++) {
		var c = ca[i];
		while (c.charAt(0) === ' ') { c = c.substring(1,c.length); }
		if (c.indexOf(nameEQ) === 0) {return c.substring(nameEQ.length,c.length); }
	}
	return null;
};

FLYFI.eraseCookie = function(name) {
	FLYFI.createCookie(name,"",-1);
};

// Preferences

FLYFI.Preferences = function(cookieName) {    // class
    // keys and values are strings and must not contain pipes ("|")
    var PREF_SEPARATOR = "||";
    var KEY_SEPARATOR = "|";
    var DICT_SEPARATOR = "::";
    var DICT_KEY_SEPARATOR = ":";
    var DICT_PREFIX = '#';
    
    var self = this;
    self.cookieName = cookieName;
    self.prefs = [];

    self.getTrackForLibrary = function(libraryID) {
        return self.getDict(FLYFI.LIBRARY_TRACK, 'lib' + libraryID);
    };
    self.setTrackForLibrary = function(libraryID, trackID) {
        self.setDict(FLYFI.LIBRARY_TRACK, 'lib' + libraryID, trackID);
    };
    
    self.getBoolean = function(key, defaultValue) {
        var value = self.prefs[key];
        if (typeof(value) == 'undefined') {
            return defaultValue;
        }
        return value == 'true';
    };
    self.setBoolean = function(key, value) {
        self.prefs[key] = value.toString();
        self.saveToCookie();
    };
    
    self.getDict = function(key, subKey, defaultValue) {
        var dict = self.prefs[DICT_PREFIX + key];
        var value;
        if (dict) {
            value = dict[subKey];
        }
        if (typeof(dict) == 'undefined' || typeof(value) == 'undefined') {
            return defaultValue;
        }
        return value;
    };
    self.setDict = function(key, subKey, value) {
        var dict = self.prefs[DICT_PREFIX + key];
        if (!dict) {
            dict = [];
            self.prefs[DICT_PREFIX + key] = dict;
        }
        dict[subKey] = value;
        self.saveToCookie();
    };
    
    self.getFloat = function(key, defaultValue) {
        var value = self.prefs[key];
        if (typeof(value) == 'undefined') {
            return defaultValue;
        }
        return parseFloat(value);
    };
    self.setFloat = function(key, value) {
        self.prefs[key] = (value || value === 0.0) ? value.toString() : '';
        self.saveToCookie();
    };
    
    self.getInt = function(key, defaultValue) {
        var value = self.prefs[key];
        if (typeof(value) == 'undefined') {
            return defaultValue;
        }
        return parseInt(value, 10);
    };
    self.setInt = function(key, value) {
        self.prefs[key] = (value || value === 0) ? value.toString() : '';
        self.saveToCookie();
    };
    
    self.getString = function(key, defaultValue) {
        var value = self.prefs[key];
        if (typeof(value) == 'undefined') {
            return defaultValue;
        }
        return value;
    };
    self.setString = function(key, value) {
        self.prefs[key] = value ? value : '';
        self.saveToCookie();
    };
    
    self.loadFromCookie = function() {
        var cookieText = FLYFI.readCookie(self.cookieName);
        if (!cookieText) { return; }
        var prefsStrings = cookieText.split(PREF_SEPARATOR);
        var l = prefsStrings.length;
        for (var i = 0; i < l; ++i) {
            var parts = prefsStrings[i].split(KEY_SEPARATOR);
            var value = parts[1];
            if (parts[0].substring(0,1) == DICT_PREFIX) { // Cookie keys which start with # have dictionaries as values
                var dict = [];
                var dictEntries = value.split(DICT_SEPARATOR);
                var ll = dictEntries.length;
                for (var j = 0; j < ll; j++) {
                    var dictEntry = dictEntries[j].split(DICT_KEY_SEPARATOR);
                    dict[dictEntry[0]] = dictEntry[1];
                }
                value = dict;
            } 
            self.prefs[parts[0]] = value;
        }
    };
    
    self.saveToCookie = function() {
        var a = [];
        for (var x in self.prefs) {
            if (self.prefs.hasOwnProperty(x)) { // see http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
                var value = self.prefs[x];
                if (value !== '' || typeof(value) != 'string') {
                    if (x.substring(0,1) == DICT_PREFIX) {
                        var b = [];
                        for (var y in value) {
                            if (value.hasOwnProperty(y)) { // see http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
                                if ((y.length > 0) && value[y]) {
                                    b.push(y + DICT_KEY_SEPARATOR + value[y]);
                                }
                            }
                        }
                        if (b.length > 0) {
                            value = b.join(DICT_SEPARATOR);
                        }
                    }
                    a.push(x + KEY_SEPARATOR + value);
                }
            }
        }
        FLYFI.createCookie(self.cookieName, a.join(PREF_SEPARATOR), 10000);
    };
    
    self.loadFromCookie();  // do this at the end once the member is defined
};
FLYFI.preferences = new FLYFI.Preferences('FLYFI.Preferences');

