/*

	Copyright 2007 - Artlogic Media Limited - http://www.artlogic.net/
	All rights reserved.

*/



/*	EDIT FUNCTIONS */

function Edit() {
}

Edit.prototype = {

	// data calls for editing records

	path: "/edit",
	data_path: "/data",	// when loading the profile initially, we share the same path as data.js
	
	editor_active: false,
	
	editor_html_loaded: false,
	
	toggle_editor: function() {
		
		if (this.editor_active) {
			this.close_editor();
            if($('profile_not_live_label')) {
                $('profile_not_live_label').style.background = '';
            }
		} else {
			this.make_editable();
            if($('profile_not_live_label')) {
                $('profile_not_live_label').style.background = 'transparent url(/images/profilenotlive.png) top right no-repeat';

            }
		}
	},
	
	
	make_editable: function() {
	
		this.editor_active = true;
		
		
		//	set new profile box width
		
        $('profileBox').style.width = constants.profile_box_width_when_editing + 'px';
	
	
		//	toggle elements
		
        hide('favourites');		
        hide('searchBox');		
        show('editBox');

        hide('editProfileBtnContainer');
        show('closeEditorBtnContainer');
		
		
		//	pack data
		
        this.pack_data();
	
	},
	
	
	close_editor: function() {
	
		this.editor_active = false;
	
	
		//	restore profile box width
		
			$('profileBox').style.width = constants.profile_box_width + 'px';
			
		
		//	toggle elements
		
			show('favourites');
			show('searchBox');		
			hide('editBox');
			
			show('editProfileBtnContainer');
			hide('closeEditorBtnContainer');
	
	},
	
	
	load_editor_html: function() {
		if (!this.editor_html_loaded) {
			this.editor_html_loaded = true;
			var el = 'editBoxContents';
			var url = '/page/profile_edit_box';
			new Ajax.Updater(el, url, {
				method: 'get',
				asynchronous: true, 
				evalScripts: true,
				onComplete: function() {
//                    $('upload_user_id').value = user_id; // FIXME
				}
			});
		}
	},
	
	
	pack_data: function() {
		// request data from server and pack it into field objects
		var url = this.data_path + '/get_user?editable=1&id=' + profile_id + sessions.session_arg();
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			evalScripts: true,
			onComplete: function(req) {
            debug(req.responseText);
				var response = decodeJSON(req.responseText);
					debug(req.responseText)
				var user = response.user;
				if (response.error) {
					debug(response.error)
				} else {
					try {
						edit.set_fields(user);
					} catch(e) {
                        debug(user.full_name);
						debug('>>>' + e);
					}
				}
			},
			onFailure: function(req) {
				debug(req.responseText);
			}
		});
	},
	
	set_fields: function(data) {
//        $('upload_user_id').value = profile_id; //FIXME
		var prefix = 'editField_';
		var id, el, type, v;
		// attempt to pack all fields
		for (var field in data) {
                        debug(field);
			id = prefix + field;
			v = data[field];
            if (v == null) continue;
			if ($(id)) {
				el = $(id);
				if (el.type) {
					
					type = el.type;
					
					if (type == 'textarea') {
                        v = v.replace(/<br \/>/g, "\n");
                        v = v.replace(/&lt;/g, "<");
                        v = v.replace(/&gt;/g, ">");
                        v = v.replace(/&quot;/g, '"');
                        v = v.replace(/&#39;/g, "'");
                        v = v.replace(/&amp;/g, "&");
                        el.value = v;
                    } else if (type == 'text') {
						el.value = v;
					}
				
				}
			}
		}
		this.refresh_editable_items(data);
	},
	
	
	save: function(form_name) {
		var url = this.path + '/update_profile';
        var success_callback = function() {}; /* Default success callback
                                                 function does nothing */
        /* These forms need a confirmation popup on success */
        var forms_with_confirmation_popups = ['edit_form_about',
                            'edit_form_skill_keywords', 'edit_form_general'];

        if (forms_with_confirmation_popups.include(form_name)) {
            success_callback = function() {
                edit_win.set({
                    title: 'Modification successful.',
                    content: "You modification has been successful.",
                    buttons: [
                                ["ok", "edit_win.close()"]
                            ]
                });
            };
        }
        this.post_form(form_name, url, success_callback);
	},

    change_email_request: function() {
        var url = '/change_email/request_change';
        var postBody = Form.serialize('edit_form_email');
        this.send_ajax_post(url, postBody, function() { 
            alert("Your request was successful. A confirmation link has been sent to the email address you have submitted."); 
            });
    },

    post_job: function() {
        var url = '/jobs';
        var postBody = Form.serialize('job_submission_form');
        postBody += '&' + $('selected_job_professions').innerHTML;
        this.send_ajax_post(url, postBody, function() { 
            alert("Your job has been recorded in our database."); 
            pages.job_noticeboard();
            });
    },

    submit_job_search: function() {
        var params = Form.serialize('job_search_form');
        var url = '/jobs?' + params;
        ie_safe_ajax_updater(url, 'job_listing_container');
    },

    reset_job_search: function() {
        $('job_search_form').reset();
        $('job_keywordField').style.color = '#939a9f';
    },

    edit_job_professions: function() {
        var selected_job_professions_params = $('selected_job_professions').innerHTML;
		job_edit_win.set({
			title: 'Select professions...', 
			url: '/jobs;professions?' + selected_job_professions_params.replace(/&amp;/g, '&')
			})
    },

    upload_profile_image: function() {
        this.post_form('upload_profile_image_form', '/edit/upload_profile_image');
    },
	
	create_testimonial_item: function(form_name) {
        this.post_form(form_name, '/testimonials');
	},
	
	create_link_item: function(form_name) {
        this.post_form(form_name, '/web_links/create');
	},
	
    post_form: function(form_name, url, success_callback) {
		var postBody = '';
		
		postBody += Form.serialize(form_name);
		postBody += '&profile_id=' + profile_id;
		postBody += '&form_name=' + form_name.split('edit_form_')[1];
		postBody += sessions.session_arg();

        this.send_ajax_post(url, postBody, success_callback);
    },

    send_ajax_post: function(url, postBody, success_callback) {
        set_cursor_style('progress');
		new Ajax.Request(url, {
			method: 'post',
			postBody: postBody,
			asynchronous: true,
			evalScripts: false,
			onComplete: function(req) {
                set_cursor_style('auto');
				var response = decodeJSON(req.responseText);
				if (response.error) {
					alert(response.error);
				} else {
                    if (success_callback) { 
                        /* The success_callback parameter is optional */
                        success_callback();
                    }
                }
				edit.clear_temporary_fields();
				edit.refresh_profile();
			},
			onFailure: function(req) {
				debug(req.responseText);
			}
		});
    },
	
	clear_temporary_fields: function() {
		// clear temporary input fields...
		var temp_text_fields = ["editField_educ_name", "editField_educ_year"];
		for (var i = 0; i < temp_text_fields.length; i ++) {
			$(temp_text_fields[i]).value = "";
		}
	},

    set_sortable_with_delay: function(id, update_function) {
        window.setTimeout(function() {
                Sortable.create(id, { constraint: true, overlap: "vertical", onUpdate: update_function })
            },
            100);
    },
	
	refresh_profile: function() {
		data.get_user(user_id);
		favourites.get_favourites(user_id);
        this.set_sortable_with_delay('creditItems', edit.credit_items_update_sort);
        this.set_sortable_with_delay('testimonialsItems', edit.testimonial_items_update_sort);
	},
	
	refresh_editable_items: function(user) {
		
		// this function is called by data.get_user() and edit.set_fields(),
		// when the editor is active. It expects a 'user' object containing 
		// the user fields, e.g. {'id': 1119, etc.}
		
		if ($("editProfile")) {
            this.build_editable_items_list("educItems", user.educ, this.build_educ_row, edit.educ_items_update_sort);
            this.build_editable_items_list("testimonialsItems", user.testimonials, this.build_testimonial_row, edit.testimonial_items_update_sort);
            this.build_editable_items_list("creditItems", user.credits, this.build_credit_row, edit.credit_items_update_sort);
            this.build_editable_items_list("personalLinkItems", user.other_websites_personal, this.build_link_row, edit.link_items_update_sort);
            this.build_editable_items_list("projectLinkItems", user.other_websites_projects, this.build_link_row, edit.link_items_update_sort);
		}
	},

    build_editable_items_list: function(container_element_id, items, row_building_function, sort_callback) {
        var el = $(container_element_id);
        var rows = [];
        var item, row;
        for (var i = 0; i < items.length; i ++) {
            item = items[i];
            rows[rows.length] = row_building_function(item);
        }
        $(container_element_id).innerHTML = rows.join("\n");
        /* If we make Credits and Testimonials sortable now, it breaks the
         * layout on IE6.
         */
        if (container_element_id !== 'testimonialsItems' && container_element_id !== 'creditItems') {
            Sortable.create(container_element_id, {constraint: true, overlap: "vertical", onUpdate: sort_callback});
        }
    },

    build_educ_row: function(item) {
        row = "<li id=\"educ_item_" + item["id"] + "\" class=\"edit_educItem\">" +
            "<span class=\"name\">" + item["description"] + "</span>" +
            "<span class=\"year\">" + item["item_year"] + "</span>" +
            "<span class=\"delete\" title=\"Remove item...\" onclick=\"edit.delete_educ_item(" + item["id"] + ")\"></span>" +
            "<span class=\"edit\" title=\"Edit item...\" onclick=\"edit.edit_educ_item(" + item["id"] + ")\"></span>" +
            "</li>";
        return row;
    },

    build_testimonial_row: function(item) {
        row = "<li id=\"testimonial_item_" + item["id"] + "\" class=\"edit_testimonialItem\">" +
            "<span class=\"name\">" + item["author_name"] + "</span>" +
            "<span class=\"organisation\">" + item["author_organisation"] + "</span>" +
            "<span class=\"year\">" + item["item_year"] + "</span>" +
            "<span class=\"delete\" title=\"Remove item...\" onclick=\"edit.delete_testimonial_item(" + item["id"] + ')"></span>' +
            "<span class=\"edit\" title=\"Edit item...\" onclick=\"edit.edit_testimonial_item(" + item["id"] + ')"></span>' +
            "<span class=\"description\">" + item["testimonial"] + "</span>" +
            "</li>";
        return row;
    },

    build_credit_row: function(item) {
         row = '<li id="credit_item_' + item["id"] + '" class="edit_creditItem sortable">' + 
              '<span class="name">' + item["project_name"] + '</span>' + 
              '<span class="organisation">' + item['roles_string'] + '</span>' + 
              '<span class="year">' + item['project_year'] + '</span>' + 
              '<span class="delete" title="Remove item..." onclick="edit.delete_credit_item(' + item["id"] + ')"></span>' +
              '<span class="edit" title="Edit item..." onclick="edit.edit_credit_item(' + item["id"] + ')"></span>' +
              '<span class="description">' + item['short_description'] + '</span>' + 
             '</li>';
        return row;
    },

    build_link_row: function(item) {
         row = '<li id="link_item_' + item["id"] + '" class="edit_linkItem sortable">' + 
              '<span class="name">' + item["label"] + '</span>' + 
              '<span class="organisation">' + item["url"] + '</span>' + 
              '<span class="delete" title="Remove item..." onclick="edit.delete_link_item(' + item["id"] + ')"></span>' +
              '<span class="edit" title="Edit item..." onclick="edit.edit_link_item(' + item["id"] + ')"></span>' +
             '</li>';
        return row;
    },
	
	delete_educ_item: function(id, description) {
        edit.delete_item(id, description, "educ");	
	},

	delete_testimonial_item: function(id, description) {
        edit.delete_item(id, description, "testimonial");	
	},

	delete_link_item: function(id, description) {
        edit.delete_item(id, description, "link");	
	},

	delete_credit_item: function(id, description) {
        edit.delete_item(id, description, "credit");	
	},

    delete_item: function(id, description, item_type) {
		edit_win.set({
			title: 'Delete item...',
			content: "Are you sure you wish to remove this item?",
			buttons: [
						["delete", "edit_win.close(); edit.delete_item_confirm('" + item_type + "', " + id + ")"],
						["cancel", "edit_win.close()"]
					]
		});
    }, 

	
	delete_item_confirm: function(item_type, id) {
			var url = this.path + '/delete_item'
			var postBody = 'record_id=' + id + '&delete_type=' + item_type + '_item';
			
			new Ajax.Request(url, {
				method: 'post',
				postBody: postBody,
				asynchronous: true,
				evalScripts: false,
				onComplete: function(req) {
					var response = decodeJSON(req.responseText);
					if (response.error) {
						alert(response.error);
					}
					edit.clear_temporary_fields();
					edit.refresh_profile();
				},
				onFailure: function(req) {
					debug(req.responseText);
				}
			});
	},
	
	edit_educ_item: function(id) {
		edit_win.set({
			title: 'Edit item...', 
			url: '/edit_win/edit_educ_item/?id=' + id
			})
	},
	
	add_testimonial_item: function(id) {
		edit_win.set({
			title: 'Add item...', 
			url: '/testimonials/new'
			})
	},
	
	add_link_item: function(id) {
		edit_win.set({
			title: 'Add item...', 
			url: '/web_links/new'
			})
	},
	
	add_credit_item: function(id) {
		edit_win.set({
			title: 'Add item...', 
			url: '/credits/new'
			})
	},
	
	edit_testimonial_item: function(id) {
		edit_win.set({
			title: 'Edit item...', 
			url: '/testimonials/' + id + '/edit'
			})
	},
	
	edit_link_item: function(id) {
		edit_win.set({
			title: 'Edit item...', 
			url: '/web_links/' + id + '/edit'
			})
	},
	
	edit_credit_item: function(id) {
		edit_win.set({
			title: 'Edit item...', 
			url: '/credits/' + id + '/edit'
			})
	},

    edit_professions: function() {
		edit_win.set({
			title: 'Edit your list of professions...', 
			url: '/users/' + user_id + '/professions'
			})
    },

    edit_email: function() {
        edit_win.set({
            title: 'Change your email address',
            url: '/change_email/form'
        })
    },

    edit_password: function() {
        edit_win.set({
            title: 'Change your password',
            url: '/edit/show_password_form'
        })
    },
	
	educ_items_update_sort: function() {
        edit.items_update_sort("edit_educItem", "education_and_skills");
	},

	testimonial_items_update_sort: function() {
        edit.items_update_sort("edit_testimonialItem", "testimonials");
        Sortable.create('testimonialsItems', { 
                constraint: true,
                overlap: "vertical", 
                onUpdate: edit.testimonial_items_update_sort 
                });
	},

    link_items_update_sort: function() {
        edit.items_update_sort("edit_linkItem", "web_links");
    },

    credit_items_update_sort: function() {
        edit.items_update_sort("edit_creditItem", "credits");
        Sortable.create('creditItems', { 
                  constraint: true, 
                  overlap: "vertical",
                  onUpdate: edit.credit_items_update_sort 
                  });
    },

	items_update_sort: function(list_element_class, table_name) {
		var sorts = [];
		var els = document.getElementsByClassName(list_element_class);
		var el;
		for (var i = 0; i < els.length; i ++) {
			el = els[i];
			sorts[sorts.length] = edit.extract_id(el.id);
		}
		edit.update_sort_order(table_name, sorts.join(","));
	},
	
	extract_id: function(t) {
		// extracts an ID from a string, assuming that the ID
		// is always the last item in an underscore-separated list, e.g.:
		// item_1, educ_item_2  returns 1 & 2, respectively
		var a = t.split("_");
		return parseInt(a[a.length - 1]);
	},
	
	update_sort_order: function(table, ids) {
		var url = this.path + '/update_sort_order?table=' + table +
		"&ids=" + ids;
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			evalScripts: false,
			onComplete: function(req) {
				var response = decodeJSON(req.responseText);
				if (response.error) {
					debug(response.error);
				} else {
					debug('sort order request completed');
					edit.refresh_profile();
				}
			}
		});
	},

    /* This function checks if an element with id parent_element_id has a direct
     * child with an id of seeked_element_id and pops up a message if it is
     * the case.  
     */
    element_has_child: function(parent_element_id, seeked_element_id, message) {

        var has_child = $(parent_element_id).childElements().find(function(element) {
           return (element.id == seeked_element_id) ? true : false;
        });

        if (has_child) {
            alert(message);
            return true;
        } else {
            return false;
        }
    },

    select_user_profession: function(element_id) {

        var new_element_id = 'selected_' + element_id;
        var already_selected_message = $(element_id).innerHTML.strip() + ' has already been selected.';
        if (this.element_has_child('selected_professions_area', new_element_id, already_selected_message)) {
            return false;
        }

        var li = document.createElement('li');
        li.id = new_element_id;
        li.className = 'sortable';

        var nameSpan = document.createElement('span');
        li.appendChild(nameSpan);
        nameSpan.className = 'name';
        nameSpan.innerHTML = $(element_id).innerHTML;

        var deleteSpan = document.createElement('span');
        li.appendChild(deleteSpan);
        deleteSpan.className = 'delete';
        deleteSpan.onclick = function() { $(li.id).remove(); };
        deleteSpan.title = 'Remove item...';
        $('selected_professions_area').appendChild(li);
        Sortable.destroy('selected_professions_area');
        Sortable.create('selected_professions_area', { 
                            constraint: true, 
                            overlap: 'vertical'
                            });
    },

    serialize_professions: function() {
        var list = [];
        
        $('selected_professions_area').childElements().each(function(element, i) {
           list.push(element.id + '=' + i);
        });

        return list.join('&');
    },

    save_professions: function() {
	    var url = '/users/' + user_id + '/professions'
        var post_data = this.serialize_professions();
        post_data += '&profession_override=' + escape($('profession_override_field').value);
        post_data += '&_method=PUT';

		new Ajax.Request(url, {
			method: 'post',
			postBody: post_data,
			asynchronous: true,
			evalScripts: false,
			onComplete: function(req) {
                $('formatted_list_of_professions').innerHTML = req.responseText;
				edit.refresh_profile();
			},
			onFailure: function(req) {
				debug(req.responseText);
			}
		});
    },

    save_job_professions: function() {
        $('selected_job_professions').innerHTML = this.serialize_professions();
        var profession_names = [];
        $('selected_professions_area').childElements().each(function(li) {
           var span = li.firstDescendant();
           if (span.innerHTML)
           profession_names.push(span.innerHTML.strip());
        });
        $('selected_job_professions_names').innerHTML = profession_names.join(', ');
    },

	create_credit_item: function(form_name) {
	    var url = '/credits/create';
		var post_data = Form.serialize(form_name) + '&';
        post_data += this.serialize_professions();

        this.send_ajax_post(url, post_data);
	},

	update_credit_item: function(form_name) {
	    var url = '/credits/' + $F('credit_item_id');
		var post_data = Form.serialize(form_name) + '&_method=PUT&';
        post_data += this.serialize_professions();

        this.send_ajax_post(url, post_data);
	},

    send_message: function(form_name) {
	    var url = '/contact/send_message';
		var post_data = Form.serialize(form_name);
        post_data += '&recipient_user_id=' + profile_id;
        this.send_ajax_post(url, post_data);
    },

    show_request_change_from_admin_form: function(attribute_name) {
		edit_win.set({
			title: 'Request ' + attribute_name + ' change from the admin', 
			url: '/profile_change_request/form?attribute_name=' + attribute_name
			})
    },

    request_change_from_admin: function() {
	    var url = '/profile_change_request/send_request';
		var post_data = Form.serialize('request_change_from_admin_form');
        this.send_ajax_post(url, post_data);
    },

    show_report_profile_form: function(reported_user_id) {
		edit_win.set({
			title: 'Report a profile to the administrator', 
			url: '/report_profile/form?reported_user_id=' + reported_user_id
			})
    },

    show_contact_form: function() {
		edit_win.set({
			title: 'Send a message', 
			url: '/contact/form?recipient_user_id=' + profile_id
			})

    },

    report_profile: function() {
	    var url = '/report_profile/send_report';
		var post_data = Form.serialize('report_profile_form');
        this.send_ajax_post(url, post_data, function() { edit_win.close(); });
    },

    make_my_profile_live: function() {
        var url = '/edit/make_profile_live';
        new Ajax.Request(url, {
            method: 'get',
            asynchronous: true,
            evalScripts: false,
            onComplete: function(req) {
				edit.refresh_profile();
            },
            onFailure: function(req) {
                edit_win.set_content('Could not make your profile active: ' + req.responseText);
            }
        });
    },

    remove_profile_photo: function() {
        new Ajax.Request('/edit/remove_profile_photo', {
            method: 'get',
            asynchronous: true,
            evalScripts: false,
            onComplete: function(req) {
				var response = decodeJSON(req.responseText);
				if (response.error) {
                    alert(response.error);
				} else {
                    edit.refresh_profile();
				}
            },
            onFailure: function(req) {
                alert("The request has failed");
            }
        });
    }
}

var edit = new Edit();


function EditWindow(window_id) {
    this.window_id = window_id;
} 

EditWindow.prototype = {
    
    set_title: function(t) {
        $(this.window_id + 'Title').innerHTML = t;
    },
    
    set_content: function(t) {
        var div = document.createElement('div');
        div.innerHTML = t;
        $(this.window_id + 'Content').innerHTML = '';
        $(this.window_id + 'Content').appendChild(div);
    },
    
    get_content: function() {
        return $(this.window_id + 'Content').innerHTML;
    },
    
    open: function() {
        this.hide_selects();
        show($(this.window_id));
    },
    
    close: function() {
        hide($(this.window_id));
        this.show_selects();
    },

    hide_selects: function() {
        this.set_selects_visibility('hidden');
    },

    show_selects: function() {
        this.set_selects_visibility('visible');
    },

    set_selects_visibility: function(visibility) {
        /* Workaround for FF2 bug: when displaying layers on top of select
         * buttons, these are not covered by the layer. Therefore we provide
         * this function to hide the selects.
         *
         * The selects are there only when logged in as an alumni and the
         * profile has been loaded. */
        $w('course_select email_visibility_select region_select phone_number_visibility_select region').each(function(name) {
            var element = document.getElementsByName(name).item(0);
            if (element) {
                element.style.visibility = visibility;
            }
        });
    },
    
    set: function(params) {
        if (params.url && params.url.startsWith('/credits')) {
            $(this.window_id).style.top = '25px';
        } else if (params.url && (params.url.startsWith('/report_profile') ||
                        params.url.startsWith('/contact/'))) {
            $(this.window_id).style.top = '124px';
            $(this.window_id).style.left = '400px';
        } else {
            $(this.window_id).style.top = '124px';
        }

        el = $(this.window_id + 'Content')
        var title = (params.title) ? params.title : '';
        this.set_title(title);
        
        if (params.content) {
            this.set_content(params.content);
        }
        
        if (params.buttons) {
            /* params.buttons expects an array where each
             * item is itself an array of [type, action]
             */
            var btns = [];
            var btn;
            var item;
            for (var i = 0; i < params.buttons.length; i ++) {
                item = params.buttons[i];
                btn = templates.render('btn_' + item[0], {onclick: item[1]});
                btns[btns.length] = btn;
            }
            var content = this.get_content();
            content = '<div class="padded">' + content + '</div>' +
                    '<div class="padded">' + btns.join("") + '</div>';
            this.set_content(content);
        }
        
        if (params.url) {
            var url = params.url;
            /* Using Ajax.Updater does NOT work in this context with IE6.
               We use an Ajax.Request with a response handler that is a
               workaround for the infamous IE6 innerHTML bug.
               */
            var edit_win = this;
            new Ajax.Request(url, {
                method: 'get',
                asynchronous: true,
                evalScripts: false,
                onComplete: function(req) {
                    edit_win.set_content(req.responseText);
                    Sortable.create('selected_professions_area', { constraint: true, overlap: 'vertical' });
                },
                onFailure: function(req) {
                    edit_win.set_content('Could not load the content of the window: ' + req.responseText);
                }
            });
        }
        this.open($(this.window_id));
    }
};

var edit_win = new EditWindow('editWindow');
var job_edit_win = new EditWindow('jobEditWindow');

/* END */
