/*

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

*/



/* CONSTANTS */


var constants = {
	
	
	//	items which do not change: default widths of elements, etc.
	
	profile_box_width: 586,
	profile_box_width_when_editing: 420,
	
	main_accordian_results_height: 200,
	main_accordian_secondary_results_height: 155,
	
	no_results_found_el: '<ul><li class="msg">Please select from the search options on the left</li></ul>',
	empty_favourites_list: '<li class="msg">You will need to log in to select Favourites.</li>',
	
	input_fields_disabled_color: '#939a9f',
	input_fields_enabled_color: '#222222'
	
	
}


/*	GENERAL  */
	
	var debug_active = false;
	
	var debug = function() {
		if (debug_active && console) {
			//	log to Firebug console
			console.log(arguments);
		}
	}
	
	var in_development = function() {
		alert('This feature is currently in development');
	}


	var concat_ws = function() {
		if (arguments.length>1) {
			var a = arguments;
			var t = "";
			var x=a[0]; // the separator character
			for (var i = 1; i < a.length; i ++) {
				if (a[i] + "" != "") {
					if (t != "") {
						t += x;
					}
					t += a[i] + "";
				}
			}
			return t;
		}
	}


	var decodeJSON = function(t) {
		return eval('(' + t + ')');
	}
	
	
	var addEvent = function(el, evType, fn, useCapture) {
		el["on" + evType] = fn;
		return;
	}
	
	
	var checkHash = function() {
		var l = document.location.hash;
		if (l) {
			var s = l.split('#');
			if (s.length > 1) {
				openTab(s[1]);
			}
		} else {
			openTab('About');
		}
	}
	
	
	var addClass = function(el, className) {
		var classes=el.className.toString();
		if ((" " + classes + " ").indexOf(" " + className + " ") == -1) {
			var newClasses = (classes == "") ? className : classes + " " + className;
			el.className=newClasses;
		}
	}
	
	var  removeClass = function(el, className) {
		var classes=el.className.toString().split(" ");
		var newClasses = new Array();
		for (var i = 0; i < classes.length; i++) {
			if (classes[i] != className) {
				newClasses[newClasses.length] = classes[i];
			}
		}
		el.className = newClasses.join(" ");
	}
	
	var hide = function(el) {
		addClass($(el), 'hidden');
	}
	
	var show = function(el) {
		removeClass($(el), 'hidden');
	}
	

	var set_cookie = function(cookieName, cookieValue, nDays, path) {
		var today = new Date();
		var expire = new Date();
		if (nDays == null || nDays == 0) {
			nDays = 1;
		}
		expire.setTime(today.getTime() + 3600000*24*nDays);
		if (typeof path == "undefined") {
			document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
		} else {
			document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString() + ";path=" + escape(path);
		}
	}

	var get_cookie = function(cookieName) {
		var theCookie = "" + document.cookie;
		var ind = theCookie.indexOf(cookieName);
		if (ind == -1 || cookieName == "") {
			return "";
		}
		var ind1 = theCookie.indexOf(';', ind);
		if (ind1 == -1) {
			ind1 = theCookie.length;
		}
		var v = unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
		if (v == '') {
			return;
		} else {
			return v;
		}
	}

	var openTab = function(which) {
		
		var el;
		var els = $$('.tabPane');
		for (var i= 0; i < els.length; i ++) {
			el = els[i];
			el.style.display = "none";
		}
		
		if ($('profileInfo' + which)) {
			$('profileInfo' + which).style.display = "block";
		} else {
			$('profileInfoAbout').style.display = "block";
		}
		
		var tabs = $$('.tab');
		for (var i= 0; i < tabs.length; i ++) {
			removeClass(tabs[i], 'active');
		}
		
		if ($('tab' + which)) {
			addClass($('tab' + which), 'active');
		}
	
	}



/*	TABS  */


	var tab = {
	
		//	functions which  control tabs
		
		
		//	provide an extensible method whereby we can refer to a group of
		//	tabs as 'profile' or 'edit', and the relevant tab object is then
		//	got from the objects prefix and name. For each group, the first
		//	item of the array object is the 'tab prefix' and the second the
		//	content prefix...
		
			groups: {
				
				'profile': {
					contentContainerID: 'editProfileTabContent',
					tabClassName: 'profileTab', 
					contentClassName: 'profileTabContent',
					tabPrefix: 'tab', 
					contentPrefix: 'profileInfo'
				},
				
				'edit': {
					contentContainerID: 'profileTabContent',
					tabClassName: 'editTab', 
					contentClassName: 'editTabContent',
					tabPrefix: 'editTab', 
					contentPrefix: 'editTabContent'
				},

	            'jobs': {
					contentContainerID: 'jobsTabContent',
					tabClassName: 'jobsTab', 
					contentClassName: 'jobsTabContent',
					tabPrefix: 'jobsTab', 
					contentPrefix: 'jobsTabContent'
				}
				
			},
		
		
		//	methods
		
			open: function(group, name) {
			
				// to open a tab, use the syntax "tab.open('profile', 'Education')"
				// where the first parameter is the group (see above), and the second
				// parameter the name of the tab
				
				var tab_data = this.groups[group];
				
				var tabEls = document.getElementsByClassName(tab_data.tabClassName);
				var contentEls = document.getElementsByClassName(tab_data.contentClassName);
				
				for (var i = 0; i < tabEls.length; i ++) {
					// set tab to inactive and hide content
					removeClass(tabEls[i], 'active');				
					hide(contentEls[i]);
				}
				
				// activate named tab and show content
				addClass($(tab_data.tabPrefix + name), 'active');
				show(tab_data.contentPrefix + name);
                /* We make Credits in Testimonials sortable after a short delay
                 * otherwise it breaks the layout on IE6.
                 */
                if (name === 'Credits' && $('creditItems') ) {
                    edit.set_sortable_with_delay('creditItems', edit.credit_items_update_sort);
                } else if (name === 'Testimonials' && $('testimonialsItems')) {
                    edit.set_sortable_with_delay('testimonialsItems', edit.testimonial_items_update_sort);
                }
			}
	
	
	}





	
/*	ACCORDIANS */
	
	function accordion(el) {
		if ($('visible') == el) {
			return;
		}
		if ($('visible')) {
			
			//	hide all scrollbars on 'choices' elements
				var els = $$('.choices');
				for (var i = 0; i < els.length; i ++) {
					els[i].style.overflow = 'hidden';
				}
			
			
			//	animate accordian elements
				var eldown = el.parentNode.id+'-body';
				var elup = $('visible').parentNode.id+'-body';
				new Effect.Parallel(
					[
						new Effect.SlideUp(elup),
						new Effect.SlideDown(eldown)
					],
					{
						duration: 0.1
					}
				);
				$('visible').id = '';
			
			
			//	show scrollbars on 'choices' elements for this panel only
			var active_list_classname = el.parentNode.id + '-list';
			window.active_list_el = document.getElementsByClassName(active_list_classname)[0];
			
			window.setTimeout("window.active_list_el.style.overflow = 'auto'", 100);
		
		}
		
		el.id = 'visible';
	
	}


	function jobAccordion(el) {
		if ($('visible2') == el) {
			return;
		}
		if ($('visible2')) {
			
			//	hide all scrollbars on 'choices' elements
			var els = $$('.choices2');
			for (var i = 0; i < els.length; i ++) {
				els[i].style.overflow = 'hidden';
			}
			
			//	show scrollbars on 'choices' elements for this panel only
			var els = $('visible2').getElementsByTagName('div');
			for (var i = 0; i < els.length; i ++) {
				els[i].style.overflow = 'auto';
			}
			
			var eldown = el.parentNode.id+'-body';
			var elup = $('visible2').parentNode.id+'-body';
			new Effect.Parallel(
			[
				new Effect.SlideUp(elup),
				new Effect.SlideDown(eldown)
			], {
				duration: 0.1
			});
			$('visible2').id = '';
		}
		el.id = 'visible2';
	}



/*	BUTTONS  */

	var xbutton = function(url, name, alt) {
		
		var t = '';
		var image = name + '.png';
		var rollover_image = name + '_on.png';
		
		t += '<div class="rollover" style="background-image: url(/images/buttons/' + rollover_image + ');margin-left:7px">';
		t += '<a href="' + url + '"><img src="/images/buttons/' + image + '" alt="' + alt + '" /></a>';
		t += '</div>';
		
		document.write(t);
		
	}





/*	MAIN ONLOAD HANDLER  */
	
	function init() {
		
		//	refresh user session (and again, every minute)
			
			sessions.refresh_session();
            $('remove_account_link').hide();
            $('help_link').hide();
			var session_interval = window.setInterval("sessions.refresh_session()", 60000); // every 60 seconds
	
		
		// hide all elements apart from the one with id visible
			var acc = document.getElementById('accordion');
			var apanels = acc.getElementsByTagName('div');
			for (i = 0; i < apanels.length; i++) {
				if (apanels[i].className == 'panel_body') {
					apanels[i].style.display = 'none';
				}
			}
			var avis = document.getElementById('visible').parentNode.id+'-body';
			document.getElementById(avis).style.display = 'block';
		
		
		//	load 'home' content
		
            if ( ! (
                document.URL.match(/reset_password\/password_form/) ||
                document.URL.match(/registration\/confirm_visitor_registration/) ||
                document.URL.match(/registration\/confirm_alumni_registration_request/) ||
                document.URL.match(/registration\/confirm_alumni_registration/)
            ) && do_load_homepage ) {
                pages.home()
            }
		
		
		//	set search panels
			
			search_panels.init();
			
		
		//	functions to select the currenty selected tab
		
			/*
			var els = $$('.tabPane');
			var el;
			for (var i= 0; i < els.length; i ++) {
				el = els[i];
				el.style.display = "none";
			}
			
			checkHash(); // if there is an anchor sent to the page, it should contain the selected tab... Call it
			*/
			
			
		
		//	watch search fields for changes

			window.setInterval("data.watch_for_changes()", 1500);
		
		
		//	do we need to auto-load a profile or any other data?
		
			if ($('auto_load_profile_name').value != '') {
				$('nameField').value = $('auto_load_profile_name').value;
				// that's all we need to do: the data.watch_for_changes() 
				// function will submit the data:
				data.watch_for_changes();
			}

			if ($('auto_load_profile_id').value != '') {
				$('idField').value = $('auto_load_profile_id').value;
				// that's all we need to do: the data.watch_for_changes() 
				// function will submit the data:
				data.watch_for_changes();
			}

        // Populate search with latest alumnis
        ie_safe_ajax_updater('/data/get_latest_alumnis', 'results_list');

	}
	
//    addEvent(window, "load", init);
    window.onload = init;
	
	
//	ALIASES (to cut down bandwidth)

	var su = function(id, obj) {
		return search_panels.select_user(id, obj);
	}

	
	
/* TEMPLATES
 * html snippits for use with Prototype Template mechanism
 * 
 * Example:
 * 	var t = new Template('The TV show #{title} was created by #{author}.');
 * 	var data = {title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };
 * 	t.evaluate(show);
 * 	-> The TV show The Simpsons was created by Matt Groening.
 * 
 */

	var templates = {
		
		render: function(name, data) {
			/* renders an html template with the supplied data.
			 * Syntax:
			 * templates.render('btn_ok', {onclick: myfunction});
			 */
			var t = this[name];
			return t.evaluate(data);
		},
		
		btn_ok: new Template(
			'<div class="left pr10">' +
			'<div class="rollover" style="margin: 0pt; background-image: url(/images/buttons/ok_on.png);">' +
			'<a onclick="#{onclick}" href="#"><img alt="OK" src="/images/buttons/ok.png"/></a>' +
			'</div>' +
			'</div>'
			),
		
		btn_cancel: new Template(
			'<div class="left pr10">' +
			'<div class="rollover" style="margin: 0pt; background-image: url(/images/buttons/cancel_on.png);">' +
			'<a onclick="#{onclick}" href="#"><img alt="Cancel" src="/images/buttons/cancel.png"/></a>' +
			'</div>' +
			'</div>'
			),
		
		btn_delete: new Template(
			'<div class="left pr10">' +
			'<div class="rollover" style="margin: 0pt; background-image: url(/images/buttons/delete_on.png);">' +
			'<a onclick="#{onclick}" href="#"><img alt="Delete" src="/images/buttons/delete.png"/></a>' +
			'</div>' +
			'</div>'
			),
		
		edit_win_contents_msg: new Template(
			'<div class="rollover" style="margin: 0pt; background-image: url(/images/buttons/save_on.png);">' +
			'<a onclick="edit.save(\'edit_educ_item\')" href="#"><img alt="Edit" src="/images/buttons/save.png"/></a>' +
			'</div>'
			)
		
	}

function ie_safe_ajax_updater(url, element_id) {
    /* 
    This is a workaround for IE's broken innerHTML implementation.
    */
    new Ajax.Request( url, {
            method: 'get',
            asynchronous:true, 
            evalScripts:false,
            onComplete: function(req) {
                var div = document.createElement('div');
                div.innerHTML = req.responseText;
                $(element_id).innerHTML = '';
                $(element_id).appendChild(div);
            }
        }); 
}


//	POP-UP WINDOWS FOR GENERAL USE

var fl_win = function(params) {
    return fl_popUpWin(params);
}

var fl_popUpWins = [];

function fl_popUpWin(url, name, w, h, scrollbars, resizable, menubar, status) {
    if (typeof url == 'object') {
        /*
            As of Nov 2007, you may use the shorter alias to this function, 'fl_win',
            and may specify parameters as an object, using only the first argument, e.g.:
                
                fl_win({
                    url: '/my_popup.html'
                });
                
                fl_win({
                    url: '/my_popup.html',
                    name: 'PopUp',
                    width: 500,
                    height: 400,
                    scrollbars: true,
                    resizable: true,
                    menubar: true,
                    status: true
                });
                
            No parameters are required, however 'url' is highly recommended!
            When using the 'params' method, 'fl_win' is an alias for 'fl_popUpWin', e.g.:
            fl_popUpWin({...params...}) will work in the same manner

            NOTE: the name must not have spaces in it.
        */
        // set up defaults
        var params = url;
        var url = (params.url) ? params.url : "http://www.artlogic.net/flgui/images/shim.gif";
        var name = (params.name) ? params.name : "Window_" + fl_popUpWins.length;
        var w = (params.width) ? params.width : 550;
        var h = (params.height) ? params.height : 550;
        var scrollbars = (params.scrollbars) ? "yes" : "no"
        var resizable = (params.resizable) ? "yes" : "no"
        var resizable = (params.resizable) ? "yes" : "no"
        var menubar = (params.menubar) ? "yes" : "no"
        var status = (params.status) ? "yes" : "no"
    } else {
        var w = (w) ? w : 550;
        var h = (h) ? h : 550;
        var scrollbars = (scrollbars) ? "yes" : "no";
        var resizable = (resizable) ? "yes" : "no";
        var menubar = (menubar) ? "yes" : "no";
        var status = (status) ? "yes" : "no";
    }
    var l=(screen.availWidth-w)/2;
    var t=((screen.availHeight-h)/3)-40;
    if (!fl_popUpWins[name] || fl_popUpWins[name].closed) {
        fl_popUpWins[name] = window.open(url,name,'width=' + w + ',height=' + h + ',top=' + t + ',left=' + l + ',scrollbars=' + scrollbars + ',resizable=' + resizable + ',menubar=' + menubar + ',status=' + status);
        if (fl_popUpWins[name]) { // the window may have been blocked by a pop-up blocker
            fl_popUpWins[name].focus();
        } else {
            alert("Please ensure that you allow pop-up windows for this application as they may contain important messages or functionality. Please update your browser preferences and reload this page.");
        }
    } else if (fl_popUpWins[name]) { // the window may have been blocked by a pop-up blocker
        fl_popUpWins[name].focus();
    }
}

function terms_and_services_popup() {
    fl_popUpWin('/page/terms_popup', 'terms', 570, 610, true, true);
}

function set_cursor_style(style) {
    document.body.style.cursor = style;
}

function get_return_handler(form_submission_function) {
    return function(e) {
        var code = (e.keyCode) ? e.keyCode : e.which;
        if (code == 13 || code == 3) {
            form_submission_function();
        }
    }
}

function set_return_handlers(form_id, form_submission_function) {
    $(form_id).getInputs().each(function(element) {
        element.onkeypress = get_return_handler(form_submission_function);
    });
}


/* END */
