
//JS for LibAnswers widget

//set-up namespace if necessary
var springSpace = springSpace || {};
springSpace.la = springSpace.la  || {};
springSpace.la.css_loaded = springSpace.la.css_loaded || 0;

//TOPIC Content items
springSpace.la.showAllTopics = function(contentid) {
	springSpace.jq('#'+contentid+' .hidden').removeClass('hidden').attr('aria-hidden', false);
	springSpace.jq('#'+contentid+' .s-la-topic-toggle').remove();
	return false;
}


if (typeof springSpace.la.widget_2552 == 'undefined') {
	
	springSpace.la.widget_2552 = function() {
		
		this.id = 2552;
		this.iid = 1208;
		this.divselector = '#s-la-widget-'+this.id;
		this.$container = springSpace.jq(this.divselector);
		protocol = (!window.XDomainRequest) ? 'https:' : location.protocol; //IE9 stupid CORS thing
		this.apiDomain = protocol+'//api2.libanswers.com';
		this.systemDomain = '//montana.libanswers.com';
		this.css_url = this.apiDomain+'/css/LibAnswers_widget.css';
		this.usecss = 1;
		this.customcss = "";
		this.solrUrl = 'https://search-platform.libapps.com/la2/';
		this.link_target = '_parent';
		
		this.widgethtml = "<section id=\"s-la-widget-body-2552\"><div class=\"s-la-widget-header\"><h1>Email MSU Library<\/h1><\/div><div id=\"s-la-content-form-2552\" class=\"s-la-content-form s-la-content\"><div id=\"s-la-askform-2552\" class=\"s-la-askform s-la-askform-qu-696\"><form name=\"s-la-askform-form_2552\" id=\"s-la-askform-form_2552\" method=\"post\"><input type=\"hidden\" name=\"instid\" value=\"1208\">\n\t\t\t\t<input type=\"hidden\" name=\"quid\" value=\"696\">\n\t\t\t\t<input type=\"hidden\" name=\"qlog\" value=\"0\">\n\t\t\t\t<input type=\"hidden\" name=\"source\" value=\"4\"><input type=hidden name=ua value=1 \/><input type=hidden name=ip value=1 \/><fieldset id=\"s-la-askform-section-1885\" class=\"\"><legend>Email MSU Library<\/legend><div class=\"form-group pquestion_wrap\"><label for=\"pquestion_2552\" class=\"control-label \">Question<\/label><input class=\"form-control \" type=text id=\"pquestion_2552\" name=\"pquestion\" value=\"\"  \/><\/div><div class=\"form-group pdetails_wrap\"><label for=\"pdetails_2552\" class=\"control-label \">More Detail\/Explanation<\/label><textarea class=\"form-control \" type=text id=\"pdetails_2552\" name=\"pdetails\" ><\/textarea><\/div><div class=\"form-group val5_wrap\"><label for=\"val5_2552\" class=\"control-label \">What resources have you tried so far?<\/label><input class=\"form-control \" type=text id=\"val5_2552\" name=\"val5\" value=\"\"  \/><\/div><\/fieldset><fieldset id=\"s-la-askform-section-1886\" class=\"\"><legend>Your Info<\/legend><div class=\"form-group pname_wrap\"><label for=\"pname_2552\" class=\"control-label \">Your Name<\/label><input class=\"form-control \" type=text id=\"pname_2552\" name=\"pname\" value=\"\"  \/><\/div><div class=\"form-group pemail_wrap\"><label for=\"pemail_2552\" class=\"control-label \">Email<span class=\"reqnote\"> *<\/span><\/label><input class=\"form-control  required\" type=email id=\"pemail_2552\" name=\"pemail\" value=\"\" aria-required=\"true\" \/><\/div><div class=\"form-group val1_wrap\"><label for=\"val1_2552\" class=\"control-label \">Your Location<\/label><select class=\"form-control \" name=\"val1\" id=\"val1_2552\" >\n\t\t\t\t\t\t\t<option value=0>Select One<\/option><option value=\"1\">On Campus<\/option><option value=\"2\">Off Campus<\/option><option value=\"3\">Outside of Bozeman<\/option><\/select><\/div><\/fieldset><div id=s-la-askform-reqnote_2552 class=s-la-askform-reqnote>Fields marked with <span class=\"reqnote\"> *<\/span> are required.<\/div><div class=form-actions><button id=s-la-askform-submit-2552 class=\"btn btn-primary s-la-askform-button\" type=submit>Submit Your Question<\/button><\/div><\/form><\/div><\/div><\/section>";
		this.activator = "<button id=s-la-widget-activator-2552 class=\"btn btn-default s-la-widget-activator\" type=button>Ask Us<\/button>";
		this.search = {};
		this.question = {};
		this.chatwidget = {};
		this.cascadeServer = "https:\/\/cascade2.libchat.com:443";
				
		//console.log('widget:'+this.id);
		
		//!load stylesheet if desired
		if (this.usecss == 1 && springSpace.la.css_loaded == 0) {
			if(document.createStyleSheet) {
			    try { document.createStyleSheet(this.css_url); } catch (e) { }
			}
			else {
			    var css_link = springSpace.jq("<link>", { 
				    rel: "stylesheet", 
				    type: "text/css", 
				    href: this.css_url
				});
				css_link.appendTo('head');
			}
			springSpace.la.css_loaded = 1;
		}
		//write in custom css
		if (this.customcss !== '') {
			springSpace.jq('<style>'+this.customcss+'</style>').appendTo('head');
		}
				
		var that = this; //for inside event handlers
		//console.log(this);
		
				
		//set question form
		this.prepQuestionForm = function() {
			this.question.divselector = '#s-la-askform-'+this.id;
			this.question.$form = springSpace.jq(this.question.divselector+' form');
			if (this.question.$form.length == 0) { return; }
			if (typeof this.question.$form == 'undefined') { return; }
			this.question.queue_id = 696;
			this.question.errormsg = {"emailaddress":"Invalid email address.","reqfields":"Please answer all required questions.","general":"Error: Please try again."};
			if (springSpace.current_user) {
				this.question.$form.find('input[name=pemail]').val(springSpace.current_user.email);
				this.question.$form.find('input[name=pname]').val(springSpace.current_user.name);
			}
			//!submit the form
			var that = this;
			this.question.$form.submit(function(e){
				e.preventDefault();
				var $focus = '';
				var $this = springSpace.jq(this);
				//reset validation
				springSpace.jq('#s-la-askform-alert').remove();
				$this.find('.has-error').removeClass('has-error');
				$this.find('label .error-message').remove();
				$this.find('.form-control').attr('aria-invalid', false);
				
				$question = $this.find('input[name=pquestion]');
				if ($question.val() == "" && $this.find('textarea[name=pdetails]').val() == ""){ 
					that.question.markError($question, that.question.errormsg.reqfields);
					$focus = $question;
				}
		
				var emailRegex = /^(['a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$/i;
				var $email = $this.find('input[name=pemail]');
				var emailask = springSpace.jq.trim( $email.val() );
				if (emailask !== '' && !emailask.match(emailRegex)) {
					that.question.markError($email, that.question.errormsg.emailaddress);
					if ($focus === '') { $focus = $email; }
				}

				//check "required fields" are not 0 or blank
				$this.find('input[type=text].required, input[type=email].required, select.required').each(function(i){
					var $field = springSpace.jq(this);
					if ( ($field.val() == "" && $field[0].tagName == 'INPUT') || ($field.val() == "0" && $field[0].tagName == 'SELECT') ) {
						that.question.markError($field, that.question.errormsg.reqfields);
						if ($focus == '') { $focus = $field; }
					}
				});
				
				if ( $this.find('.has-error').length > 0 ) {
					$focus.focus();
					return false;
				}
				
				var $submitbutton = $this.find('button[type=submit]');
				var buttontext = $submitbutton.html();
				$submitbutton.html('Loading...').attr('disabled', true);
				
				//set referer to current page (else it gets cached)
				$this.find('input[name=pu]').val(window.location.href);
						
				springSpace.jq.ajax ({
					url: that.apiDomain+'/1.0/form/submit',
					data: $this.serialize(),
					success: function(d) {
						if (d.status == 1) {
							that.question.formAlert('success', d.message, that.question.$form).clearForm();
													} else {
							if (!d.error) { d.error = 'Error'; }
							that.question.formAlert('error', d.error, that.question.$form);
						}
						$submitbutton.html(buttontext).removeAttr('disabled');
					},
					type: 'POST',
					dataType: 'json'
				}).fail(function(){
					that.question.formAlert('error', 'Error: Please try again', that.question.$form);
					$submitbutton.html(buttontext).removeAttr('disabled');
				});	
			});
			//end submit event action
			//!set an error (msg) for the input
			this.question.markError = function($input, msg) {
				var msg_div = springSpace.jq('<div class="error-message"></div>').html(msg);
				$input.attr('aria-invalid', true).parents('div.form-group').addClass('has-error').find('label').append(msg_div).removeClass('sr-only');
			}
			//!alerts post submit
			this.question.formAlert = function(type, msg, $div) {
				if (typeof msg == 'undefined' || msg == '') { msg = (type=='error') ? 'Error' : 'Success.'; }
				var aclass = (type=='error') ? 'alert-danger' : 'alert-success';
				springSpace.jq('<div id="s-la-askform-alert" class="alert '+aclass+'" role="alert">'+msg+'</div>').insertAfter($div);
				return this;
			}
			//!clear the question form on successful submission
			this.question.clearForm = function () {
				springSpace.jq(that.question.divselector).find('.has-error').removeClass('has-error'); //reset validation
				springSpace.jq(that.question.divselector+' textarea').val('');
				springSpace.jq(that.question.divselector+' input[type=text]').val('');
				springSpace.jq(that.question.divselector+' input[type=email]').val('');
				springSpace.jq(that.question.divselector+' input[type=file]').val('');
				springSpace.jq(that.question.divselector+' select').prop("selectedIndex", 0);
				springSpace.jq(that.question.divselector+' input[type=checkbox]').prop('checked', false);
			}
			
			springSpace.jq('.s-la-widget-ask-b button').on('click', function(e){
				that.showPane('form');
			});
		
		} //end prepQuestionForm
		
		
		
			
		//write out content
					//!embed the html and attach event handlers
			this.$container.addClass('s-la-widget s-la-widget-embed').html(this.widgethtml);
								this.prepQuestionForm();
										
	} //end springSpace.la.widget
	
}


//!define the loader if we haven't already (in another widget)
if (typeof springSpace.la.widget_loader == 'undefined') {
	springSpace.la.widget_loader = function(widget_id) {
		this.widget_id = widget_id;
		var that = this;

		//check jquery version up to (not including) second decimal
		//is the current version >= minimum version
		this.minVersion = function(minv, curr) {
			var curr = curr || window.jQuery.fn.jquery;
			var c = curr.split('.');
			var m = minv.split('.');
			
			if (parseInt(c[0], 10) > parseInt(m[0], 10)) { return true; }
			else if (parseInt(c[0], 10) < parseInt(m[0], 10)) { return false; }
			else {
				if (typeof c[1] == 'undefined') { c[1] = 0; }
				if (typeof m[1] == 'undefined') { m[1] = 0; }
				if (parseInt(c[1], 10) > parseInt(m[1], 10)) { return true; }
				else if (parseInt(c[1], 10) < parseInt(m[1], 10)) { return false; }
				else { return true; }
			}
		}
		
		//load jquery into the page if necessary
		this.loadJquery = function(){
			var script_tag = document.createElement('script');
		    script_tag.setAttribute("type","text/javascript");
		    script_tag.setAttribute("src", "//code.jquery.com/jquery-1.11.1.min.js");
		    if (script_tag.readyState) { // for IE
		    	script_tag.onreadystatechange = function () {
			        if (this.readyState == 'complete' || this.readyState == 'loaded') {
			            that.scriptLoadHandler();
			        }
		    	};
		    } else {
			    script_tag.onload = that.scriptLoadHandler;
			}
		    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
		}
		
		//Called once jQuery has loaded
		this.scriptLoadHandler = function() {
		    // Restore $ and window.jQuery to their previous values and store the new jQuery in our local jQuery variable
		    if (window.jQuery) {
		    	springSpace.jq = window.jQuery.noConflict(true);
		    }
		    //load bootstrap js
		    that.boostrapLoadHandler();
		}
		
		//Bootstrap JS if we need it
		this.boostrapLoadHandler = function() {
	    	var script_tag = document.createElement('script');
	    	script_tag.setAttribute("type","text/javascript");
	    	script_tag.setAttribute("src","//api2.libanswers.com/js/LibAnswers_widget.js");	
	    	if (script_tag.readyState) { // for IE
	    		script_tag.onreadystatechange = function () {
		   	     if (this.readyState == 'complete' || this.readyState == 'loaded') {
		    	        that.loadWidget();
		      	  }
	    		};
	    	} else {
		   		script_tag.onload = that.loadWidget;
			}
	    	(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
		}
		
		//called once we have jquery + bootstrap loaded	
		this.loadWidget = function () {			
		    //springSpace.la['widget_'+that.widget_id+'_inst'] = new springSpace.la['widget_'+that.widget_id]();
		    springSpace.jq(document).ready(function(){
		    	springSpace.la['widget_'+that.widget_id+'_inst'] = new springSpace.la['widget_'+that.widget_id]();
		    });
		}
		
		if (typeof springSpace.jq == "undefined") {
			if (window.jQuery === undefined) {
				this.loadJquery();
			} else {
				if (this.minVersion('1.10', window.jQuery.fn.jquery)) {
					springSpace.jq = window.jQuery;
					if (typeof springSpace.jq.fn.typeahead == "undefined") {
						this.boostrapLoadHandler();
					} else {
						this.loadWidget();
					}
				} else {
					this.loadJquery();
				}			    
			}
		} else if (typeof springSpace.jq.fn.typeahead == "undefined") {
			this.boostrapLoadHandler();
		} else {
			this.loadWidget();
		}
	}
}

(function(){
	springSpace.la.load_2552 = new springSpace.la.widget_loader(2552);
})(); //end anonymous function