var pKey = "TL+RTUTed3z/rBI38SK2YPQct69mTKunxqga9cSBjmFB4lHaGNMBgN5J+L5m6VXh";
var available = true;
var display = "full";
var theJID = 'ask-a-librarian-general@chat.libraryh3lp.com'; // The client name
var offReg = /^(www.|libdevl.lib.){0,1}umanitoba.ca$/i; // Which sites this is local too
var offSite = ((offReg.test(window.location.hostname))? false : true); // Is it local or remote access
//offSite = false;

/* Courtesy Rob Glazebrook @ http://www.cssnewbie.com/test-for-border-radius-support/
*/
try {
jQuery(function() {
	jQuery.support.borderRadius = false;
	jQuery.each(['BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {
		if(document.body.style[this] !== undefined) { jQuery.support.borderRadius = true; }
		return (!jQuery.support.borderRadius);
	});
});
} catch (err){}
//******************************************//
function importJS(url){
	var newS = document.createElement('script');
	newS.type = 'text/javascript';
	newS.src = url;
	return newS;
}
//******************************************//
function makeForm(on_off){
	var mainD = jQuery('<div></div>');
	if (on_off == 'online'){
		var tmpD = jQuery('<div id="askA_online" class="libraryh3lp" jid="' + theJID + '"></div>');
		if (offSite){
			jQuery(tmpD).append(jQuery('<div id="askA_head"><img src="http://umanitoba.ca/libraries/images/askA_banner_sm.png" alt="Ask A Librarian"/></div>'));
		} else {
			jQuery(tmpD).append(jQuery('<div id="askA_head"><img src="/libraries/images/askA_banner_sm.png" alt="Ask A Librarian"/></div>'));
		}
		if (jQuery.support.borderRadius){
			var iTmp = jQuery('<div id="askA_frame"><iframe class="libraryh3lp-iframe" allowtransparency="true" frameborder="0" src="http://libraryh3lp.com/chat/ask-a-librarian-general@chat.libraryh3lp.com?title=&identity=librarian&theme=gota&css=http://umanitoba.ca/libraries/includes/css/ask_a_chat.css"></iframe><p>...or text us at <span style="white-space:nowrap;">204-510-2090</span></p></div>'); 
		} else {
			var iTmp = jQuery('<div id="askA_frame"><div class="inner_topright"><div class="inner_bottomleft"><div class="inner_bottomright"><iframe style="width:100%" frameborder="0" src="http://libraryh3lp.com/chat/ask-a-librarian-general@chat.libraryh3lp.com?title=&identity=librarian&theme=gota&css=http://umanitoba.ca/ip/dcooke/ask_a_chat.css"></iframe><p>...or text us at <span style="white-space:nowrap;">204-510-2090</span></p></div></div></div></div>'); 
		}
		jQuery(tmpD).append(iTmp);

		jQuery(mainD).append(tmpD);
	} else {
		var tmpD = '<div id="askA_offline">';
		if (offSite){
			tmpD += '<div id="askA_head"><img src="http://umanitoba.ca/libraries/images/askA_banner_sm.png" alt="Ask A Librarian"/></div>';
		} else {
			tmpD += '<div id="askA_head"><img src="/libraries/images/askA_banner_sm.png" alt="Ask A Librarian"/></div>';
		}
		if (jQuery.support.borderRadius){
			tmpD += '<div id="askA_frame">';
		} else {
			tmpD += '<div id="askA_frame"><div class="inner_topright"><div class="inner_bottomleft"><div class="inner_bottomright">';
		}
		if (offSite){
			tmpD += '<form method="post" action="http://umanitoba.ca/libraries/app/mail_service.php" onsubmit="return validateForm();" id="askA_form" name="askA_form">';
		} else {
			tmpD += '<form method="post" action="#" id="askA_form" name="askA_form">';	
		}
		
		tmpD += '<h3>We can\'t chat right now,</h3><p>but we\'ll get back to you on the next business day or sooner.</p>\n<p id="askA_message"></p>\n<div class="l">Your name:</div> <div class="c"><input type="text" id="askA_pName" name="askA_pName" class="text" size="20" maxlength="200" /></div> <br clear="all" /> <div class="l">Your e-mail address:</div> <div class="c"><input type="text" id="askA_pEmail" name="askA_pEmail" class="text" size="20" maxlength="200" /></div> <br clear="all" /> <div class="l">&nbsp;</div> <div class="c"><textarea id="askA_pQues" name="askA_pQues" rows="5" cols="20" class="text" wrap="virtual"></textarea></div> <br clear="all" />';
		if (offSite){
			tmpD += '<div class="center"><input type="submit" name="action" value="Send Email" /><input type="hidden" name="t" value="' + pKey + '" /></div><input type="hidden" name="l" value="1"/>';
			tmpD += '<input type="hidden" name="askA_sub" value="Ask a Librarian"/><input type="hidden" name="askA_name" value="dafref"/><input type="hidden" name="askA_dom" value="cc.umanitoba.ca"/>';
		} else {
			tmpD += '<div class="center"><input type="button" onclick="sendMsg();" name="action" value="Send Email" /></div>';
		}
		tmpD += '</form>';
		if (jQuery.support.borderRadius){
			tmpD += '</div>';
		} else {
			tmpD += '</div></div></div></div>';
		}
		tmpD += '</div>';
		tmpD = jQuery(tmpD); 

		var off = jQuery('#phpLive').offset();
		var h = off.top + (jQuery('#phpLive').height() / 2);
		tmp = jQuery('<div id="askA_load" class="loading" style="top: '+ (off.top + (jQuery('#phpLive').height() / 2)) + 'px; left: ' + (off.left + (jQuery('#phpLive').width() / 2)) + 'px;"></div>');
		jQuery(tmp).append(jQuery('<img src="http://umanitoba.ca/libraries/graphics/ajax_load/snake_circle.gif" alt="loading..." />'));
		jQuery(tmp).append('Sending...');
		jQuery(mainD).append(tmp);
		jQuery(mainD).append(tmpD);
	}
	return mainD;
}
//******************************************//
function makePopUp(on_off){
	var mainD = jQuery('<div></div>');
	var tmpA = jQuery('<a href="javascript://" onclick="askAPop(\'' + on_off + '\');"></a>');
	jQuery(tmpA).append('<img src="' + (offSite? 'http://umanitoba.ca':'') + '/libraries/images/askA_banner.png" alt="Ask a Librarian"/>');
	if (on_off == 'online'){
		jQuery(tmpA).append(jQuery('<p>Online</p>'));
	} else {
		jQuery(tmpA).append(jQuery('<p>Send an e-mail</p>'));	
	}
}
//******************************************//
function show_presence() {
	callShow = true;
	var on_off = 'offline';
	if (typeof(jabber_resources) != 'undefined'){
	  for (var i = 0; i < jabber_resources.length; ++i) {
  	  var resource = jabber_resources[i];
    	if (resource.show === 'available') {
    		on_off = 'online';
				break;  
			} 
	  }
	}
	jQuery('#phpLive').append(makeForm(on_off));
}
//******************************************//
function add2Head(obj){
	if (typeof(jQuery) == 'undefined'){
		var heads = document.getElementsByTagName('HEAD');
		heads[0].appendChild(obj);
	} else {
		jQuery('head')[0].appendChild(obj);
	}
}
//******************************************//
function check_presence() {
  var attr = theJID;
  var jid  = attr.split('@');
  var url  = 'http://api.libraryh3lp.com/presence/jid/' +  jid[0] + '/' + jid[1] + '/js';
	var js = importJS(url + '?cb=show_presence');
	add2Head(js);
}
//******************************************//
function validateEmail(theEmail){
	var myReg = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
	return myReg.test(theEmail);
}
//******************************************//
function validateForm(){
	var tName = jQuery('#askA_pName').val();
	var tEmail = jQuery('#askA_pEmail').val();
	var tMsg = jQuery('#askA_pQues').val();
	var errors = new Array();
	if (tMsg == ''){
		errors.push("You forgot to send us your question, this will help us serve you.");
	}
	if (tEmail == ''){
		errors.push("We need your e-mail address to send you an answer.");
	} else if (!validateEmail(tEmail)){
		errors.push("Your e-mail address appears incorrect. If it is not, please e-mail dafref@cc.umanitoba.ca directly.");
		if (! offSite) { logEmail(tEmail);}
	}
	if (errors.length > 0){	
		var msg = errors.join('<br />\n');
		showMsg(msg,'failed');
		return false;
	} else {
		return true;
	}
}
//******************************************//
function sendMsg(){
	var tName = jQuery('#askA_pName').val();
	var tEmail = jQuery('#askA_pEmail').val();
	var tMsg = jQuery('#askA_pQues').val();
	if (validateEmail(tEmail)){
		tMsg+= "\n\n\tSent by: " + tName + " <" + tEmail + ">";
		var thedata = {"t" : pKey ,"e_n": "whikloj","e_d": "cc.umanitoba.ca", "m" : encodeURIComponent(tMsg) , "s" : "Ask a Librarian", 'f': encodeURIComponent(tEmail)};
		disable(jQuery('#askA_form'),1);
		jQuery('#askA_load').show();
		sendEmail(thedata,'showResult(data)');
	}
}
//******************************************//
function logEmail(theE){
	var msg = 'The email address "' + theE + '" appeared and was rejected by Ask a Librarian';
	var data = {'e_n':'libwww','e_d':'umanitoba.ca','s':'Ask a Librarian Email Address Error','m' : encodeURIComponent(msg)};
	sendEmail(data);
}
//******************************************//
function sendEmail(tData){
	var URL = "/libraries/app/mail_service.php";
	var callback = ((arguments.length > 1)? arguments[1] : null);
	tData['t'] = pKey;
	var args = {
			url: URL,
			type: "POST",
			data: tData,
			dataType: 'json',
			cache: false,
			error: function(r,e){showMsg('There was an error, ' + e, 'failed');}
		};
	if (arguments.length > 1)
		eval("args['success'] = function(data,textStatus){ " + arguments[1] + ";}");

	try {
		jQuery.ajax(args);
	} catch(e){
		window.alert("major error: " + e);
	}
}	
//******************************************//
function showResult(data) {
	if (data.result == 'success'){
		showMsg('Your message has been sent.','success');
	} else {
		showMsg('There was an error sending your message.','failed');
	}
	disable(jQuery('#askA_form'),0);
	jQuery('#askA_load').hide();
}
//******************************************//
function showMsg(theText, classN){
	jQuery('#askA_message').empty();
	jQuery('#askA_message').append(theText);
	jQuery('#askA_message').attr('class',classN);
	jQuery('#askA_message').show();
}
//******************************************//
function disable(theForm,disable){
	jQuery(':input', theForm).each(function() {
		if (disable == 1)
			this.disabled = 'disabled';
		else 
			this.disabled = '';
	});
}
//******************************************//
function tryJQuery(timeOut){
	if (typeof(jQuery) == 'undefined'){
		if (timeOut < 5000){
			setTimeout("tryJQuery(" + (timeOut + 200) + ")",200);
		} else {
			var tp = document.createElement('p');
			tp.appendChild(document.createTextNode("We're sorry but chat is unavailable."));
			var php = document.getElementById('phpLive');
			if (php.length > 0){
				php[0].appendChild(tp);
			}
		}
	} else {
		jQuery(document).ready(check_presence);
	}
}		
//******************************************//

if (typeof(jQuery) == 'undefined'){
	var load = document.createElement('script');
	load.type = 'text/javascript';
	load.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
	if (available){
  	load.onload = load.onreadystatechange = function() { if (typeof(jQuery) != 'undefined') { jQuery.noConflict(); check_presence(); }};
	} else {
		load.onload = load.onreadystatechange = function() { if (typeof(jQuery) != 'undefined') { jQuery.noConflict(); var form = (display == 'full'? makeForm('offline') : makePopUp('offline')); jQuery('#phpLive').append(form);}};
	}
	add2Head(load);
} else {
	if (available){	
		jQuery(document).ready(check_presence);
	} else {
		jQuery(document).ready(function(){
			var form = (display == 'full'? makeForm('offline') : makePopUp('offline'));
			jQuery('#phpLive').append(form);});
	}
}

