

function Topics () {
	this.data = [];
}

Topics.prototype.set = function (k, v) {
	// deb('set: '+k);
	// show_json(v)
	var response = null;
	if (v && (k == 'result')) {
		this.data = v;
		response = this.data;
		
	}
	return response;
};

Topics.prototype.add = function (k, v) {
	var response = null;
	if (!v) {
		response = null;
	}
	else if (k == 'append') {
		this.data.push(v);
		response = this.data;		
	}
	else if (k == 'prepend') {
		this.data.splice(0,0,v);
		response = this.data;
	}
	return response;
};

Topics.prototype.get = function (k, v) {
	var response = null;
	response = this.data;
	if (!v) {
		response = null;
	}
	else if (k == 'id') {
// YOU ARE HERE ABOUT TO RETURN TOPIC MATCHING AN ID.
// deb('get: '+v);
		var i = 0;
		var found = false;
		while (!found && (i < this.data.length)) {
			if ((k in this.data[i]) && (this.data[i][k] == v)) {
				found = true;
				response = this.data[i]; 
			}
			i++;
		}		
	}
	return response;
};


function make_fav_link (action, topic) {
    
    var link_class = "fav_add";
    var link_button = "<img src=\"fav_add_button.gif\" class=\"save_fav_button\"></img>";
    if (action == "remove") {
        link_class = "fav_remove";
        link_button = "<img src=\"fav_remove_button.gif\" class=\"remove_fav_button\"></img>"; 
    }
    
    link =  '<a  title=\"Add to Faves list\" class=\"'+link_class+'\"';
    link += ' href=\"javascript:\{update_faves(';
    link += '\'' + action + '\'';
    link += ',\'' + encodeURIComponent(topic.id) + '\'';
    // link += ',\'' + encodeURIComponent(topic.name.replace(/\'/g, "\\\'"));
    // link += '\',\'' + encodeURIComponent(topic.property.name);
    // link += '\',\'' + encodeURIComponent(topic.property.day); // this is from topic so it includes year
    link += ');\}\">'+link_button+'</a>';
    return link;
    
}


function update_faves (action, id) {
	
    // var saved_day = get_day_str().format("MM-dd");
    if (!DayFaves.user) {
    	var content = 'I need your email address to save favorites.';
    	$('#user_form_status').html(content);
    }
    else {
	    if (action == "add") {
	        DayFaves.add_fav (DayFaves.day, id);
	    }
	    else if (action == "remove") {
	        DayFaves.remove_fav (DayFaves.day, id);
	    }
	    DayFaves.show();
    	
    }
    
}

// TODO - put these in a class

function submit_user_form() {
	       		DayFaves.user = $('#email').val();
	       		DayFaves.show_user(DayFaves.user);
	       		if (DayFaves.user) {
		       		$('#user_form').html('');       			
	       		}
	       		DayFaves.show();	
}

function show_input() {
	var email_address_input = '';
	email_address_input += '<div>Enter your email address to save favorites.</div> ';
	email_address_input += '&nbsp;&nbsp;<input id="email" class="email_input" ';
	email_address_input += 'type="text" size="40" name="email" value="" />';
	email_address_input += '<a href="javascript:{submit_user_form();}">';
	email_address_input += '<img src="ok.gif" class="user_ok_button"></img>';
	email_address_input += '</a>';
	email_address_input += '<div id="user_form_status" style="color:red;"></div>';
	$('#user_form').html(email_address_input);

	// submit is disabled for this form
   	// $('#user_form').submit(function(){
       		// return false;       		
   		// });

	$('#email').keypress(function(e) {
			var keyCode = e.keyCode || e.which; 
	        // if the key pressed is the enter or tab key
	        if ((keyCode == 9) || (keyCode == 13))
	        {
	       		DayFaves.user = $('#email').val();
	       		DayFaves.show_user(DayFaves.user);
	       		if (DayFaves.user) {
		       		$('#user_form').html('');       			
	       		}
	       		DayFaves.show();
	        }
		});
}



function Faves (day) {
	this.user = $.cookies.get('user_email');
	this.user_id = '';
	this.help_text = 'Click <img src="fav_add_button.gif" class="save_fav_button"></img> to save.';
	// this.data_request('get_id');
	if (!day) {
		this.day = make_day_str().format("MM-dd");
	}
	else {
		this.day = day;	
	}
	this.topics = [];
	this.tag = ''; // Used to append a name to the day to distiguish multiple datasets per day
    this.user_form();
	// this.data_request('get'); // requires init of faves section
}

Faves.prototype.show_user =function (user){
	var content = '';
	var email_address = '';
	email_address += '<div>';
	email_address += '<a class="user_change" href="javascript:{';
	email_address += 'show_input();';
	email_address += '}">'
	email_address += user+'</a>';
	email_address += '</div>';
	$('#user').html(email_address);
	var d = new Date;
	var future = d.add('y',10);
    $.cookies.setOptions({
//            domain: '*.wiggleback.com',
//            path: '/',
            expiresAt: future,
            secure: false
        });		
		
	$.cookies.set('user_email', user);
	this.data_request('get_id'); // update the user_id whenever user_email is updated
}

Faves.prototype.user_form = function () {	
	if (!this.user) {
		show_input();
	}
	else {
		this.show_user(this.user);		
	}
}

Faves.prototype.show = function (topics) {

	var content = '';
	var show_help = '';
	var show_button = '';
	var email_button = '';
    var fav_count = 0;
    var fav_list = '';
    this.data_request('get');
    if (topics) {
    	this.topics = topics;
    }
    var saved_faves = this.topics; //DayFaves.get_faves(this.day);
    for (var f in saved_faves) {
    	
// deb('topic: '+saved_faves[f].id);
// show_json(DayTopics.get('id',saved_faves[f].id));
    	
        fav_count++;
        fav_list += "<tr>";
        fav_list += "<td>"+ saved_faves[f].name+"</td>";
        fav_list += "<td class=\"remove_fav_position\">"+make_fav_link("remove", saved_faves[f])+"</td>";

        // fav_list += "<td>"+ saved_faves[f].name+"</td>";
        // fav_list += "<td class=\"remove_fav_position\">"+make_fav_link("remove", saved_faves[f])+"</td>";
        fav_list += "</tr>";
    }
    
	show_button = '<img id="show_card_link" class="card_link_button" src="create_card.gif" ></img>';
	email_button = '<img id="email_card_link" class="email_card_link_button" src="email_card.gif"></img>';
	content = '';
	content += '<table class="fav_options_table"><tr><td id="show_card_cell" class="show_card_cell"></td>';
	content += '<td id="email_card_cell" class="email_card_cell"></td></tr></table>';
	$('#fav_options').html(content);    	
    if (fav_count == 0) {
    	var gray_out = {
			'opacity': '0.4',
			'filter': 'alpha(opacity=40)'	
		};
		$('#show_card_cell').html(show_button);    	
	    $('#email_card_cell').html(email_button);
		$('#show_card_link').css(gray_out);
		$('#email_card_link').css(gray_out);
		show_help = this.help_text;
    }
    else {
		$('#show_card_cell').html(make_card_link(DayFaves.day, DayFaves.user_id, null, show_button));    	
	    $('#email_card_cell').html(make_card_email_link(DayFaves.day, DayFaves.user_id, null));
    }

    $('#fav_help').html(show_help);    
    $('#fav_table').html(fav_list);

};

Faves.prototype.set_help = function (content) {
	if (content) {
		this.help_text = content;
	}
	return this.help_text;
}

Faves.prototype.data_request = function (action) {

	var response = null;
	var envelope = {'result':this.topics};
    var service = "cards.php";
    var params = "&day=" + this.day;
    params += "&action=" + action;
    params += "&user=" + this.user;

	if (this.tag) {
	    params += "&card_name=" + this.tag;	
	}
	if (action != 'get') {
	    params += "&data=" + encodeURIComponent(JSON.stringify(envelope)); //encodeURIComponent();	
	}    
    // deb('action:'+action+' '+params.length+'<br>'+params);
    
    $.ajax({
        url: service + "\?",
        data: params,
        async: false,
        type: "POST",
        cache: false,
        dataType: "json",
        error: function(xobj, status, error){
            deb("<br>status: " + status);
            deb("<br>error: " + error);
        },
        context: this,			// allows 'this'  in callbacks to reference Faves instance
        success: function(r){
        	if ('result' in r) {
	        	this.topics = r['result'];
	        	response = this.topics;     		
        	}
        	else if ('user_id' in r) {
        		this.user_id = r['user_id'];
        		response = this.user_id;
        	}
        	else {
        		this.topics = null;
        	}
        }
    });
	return response;
};


Faves.prototype.get_faves = function () {
	return this.topics;
};

Faves.prototype.add_fav = function(day, topic_id){

// YOU ARE HERE - FIGURE OUT HOW TO SAVE TOPIC DATA WITH FAV
	
	var topic = DayTopics.get('id',topic_id);
	if (topic && ('id' in topic)) {
		
// deb('topic: '+topic.id);
// show_json(DayTopics.get('id',topic.id));
		
	    if (!this.topics) {
	        this.topics = [];
	    }
	    
	    // if (!(day in this.topics) || !this.topics[day]) {
	        // this.topics[day] = {};
	    // }
	    // this.topics[day][topic.id] = topic;
		this.topics.push(topic);
		return this.save_faves();
	}
	return false; 
};

Faves.prototype.save_faves = function () {
	var response = false;
	if (this.user) {
		// send topics
		this.data_request('replace');
		response = true; // TODO - test for success
	}
		
	
    return response;
};

Faves.prototype.remove_fav = function (day,topic_id) {
	// iterate topics to find matching item
	var i = 0;
	var found = false;
    while (i < this.topics.length) {
    	if (this.topics[i].id == topic_id) {
    		this.topics.splice(i,1);
    		found = true;
    	}
    	i++;
    }
	
	this.save_faves('replace');
    return false;
};


