/*
 * LU Widget API connection class
 * Developed by: Jon Carlson
*/

var apiPath = "/templates/widgets/";

/* LU class container, so this widgets API and any widgets used can be dropped in any site without affecting the sites current functionality */
var LU = {};

/* define the actions for the various tags here */
LU.LUML = {
	SocialMedia: function(el) {
		// setup the default values
		var theme = "";
		var fb = "";
		var tw = "";
		var width = "288";
		var height = "424";
		
		// grab the user-specified values (if they exist)
		var params = LU.Helper.getParams(el, "theme", "fb", "tw", "width", "height");
		if('theme' in params) theme = params['theme'];
		if('fb' in params) fb = params['fb'];
		if('tw' in params) tw = params['tw'];
		if('width' in params) width = params['width'];
		if('height' in params) height = params['height'];
		
		//if('callback' in params) callback = params['callback'];
		
		// load in the specified theme stylesheet
		if(theme != "") {
			
			if(!jQuery.browser.msie) {
				var link = jQuery("<link>");
				link.attr({
					type: "text/css",
					rel: "stylesheet",
					href: "/templates/widgets/socialmedia/themes/" + theme + ".css"
				});
				jQuery("head").append(link);
			
			} else {
				jQuery("link[href='/templates/widgets/default.css']")
					.attr("href", ("/templates/widgets/socialmedia/themes/" + theme + ".css"))
					.attr("disabled", "");
					
			}
		}
		
		// setup the structure for the social media widget
		var divHTML = '<div id="lu_sm" style="width:' + width + 'px; height:' + height + 'px;">';
		
			// decide what links to show in the widgets "header"
			var linkHTML = "";
			var displayAll = false;
			if(tw != "" && fb != "") displayAll = true;
			
			if(fb != "") {
				linkHTML += '<a href="javascript:void(0);" id="lu_sm_facebook" class="lu_sm_button';
				if(!displayAll) linkHTML += ' lu_sm_active';
				linkHTML += '"><b>Facebook</b></a>';
			}
			
			if(tw != "") {
				if(fb != "") linkHTML += '<span class="lu_sm_separator">|</span>';
				linkHTML += '<a href="javascript:void(0);" id="lu_sm_twitter" class="lu_sm_button';
				if(!displayAll) linkHTML += ' lu_sm_active';
				linkHTML += '"><b>Twitter</b></a>';
			}
			
			if(displayAll) linkHTML += '<span class="lu_sm_separator">|</span><a href="javascript:void(0);" id="lu_sm_all" class="lu_sm_button lu_sm_active"><b>All</b></a>';
		
		divHTML += ('<div id="lu_sm_top">' + linkHTML + '</div>');
		
			// decide what divs to show in the widgets "body"
			var bodyHTML = "";
			
			if(fb != "") {
				bodyHTML += '<div id="lu_sm_facebook_content" class="lu_sm_content ';
				if(!displayAll) bodyHTML += ' lu_sm_active"';
				else bodyHTML += '" style="display:none;"';
				bodyHTML += '><div class="lu_sm_feed"><div class="lu_sm_message">Loading Facebook feed...</div></div></div>';
			}
			
			if(tw != "") {
				bodyHTML += '<div id="lu_sm_twitter_content" class="lu_sm_content ';
				if(!displayAll) bodyHTML += ' lu_sm_active"';
				else bodyHTML += '" style="display:none;"';
				bodyHTML += '><div class="lu_sm_feed"><div class="lu_sm_message">Loading Twitter feed...</div></div></div>';
			}
			
			if(displayAll) bodyHTML += '<div id="lu_sm_all_content" class="lu_sm_content lu_sm_active"><div class="lu_sm_feed"><div class="lu_sm_message">Loading feeds...</div></div></div>';
		
		divHTML += ('<div id="lu_sm_bottom">' + bodyHTML + '</div>');
		
		divHTML += '</div>';
		
		jQuery(el).html(divHTML); // populate the social media widget with the new content
		
		/* need to resize the social media widget to the passed height
		 * but make sure that the CSS has loaded before doing that */
		function checkHeight(el, height) {
			var $smTop = jQuery(el).find("#lu_sm_top");
			
			if($smTop.height() > 20) {
				var actualHeight = height - $smTop.height();
				var newHeight = actualHeight;
				var $smBottom = jQuery(el).find("#lu_sm_bottom");
				var $smContent = $smBottom.find(".lu_sm_content");
				
				newHeight = newHeight - $smBottom.css("borderTopWidth").replace("px", "");
				newHeight = newHeight - $smBottom.css("borderBottomWidth").replace("px", "");
				newHeight = newHeight - $smBottom.css("padding-top").replace("px", "");
				newHeight = newHeight - $smBottom.css("padding-bottom").replace("px", "");
				$smBottom.height(newHeight);
				var usefulHeight = newHeight;
				
				newHeight = newHeight - $smContent.css("borderTopWidth").replace("px", "");
				newHeight = newHeight - $smContent.css("borderBottomWidth").replace("px", "");
				newHeight = newHeight - $smContent.css("padding-top").replace("px", "");
				newHeight = newHeight - $smContent.css("padding-bottom").replace("px", "");
				$smContent.height(usefulHeight);
				$smBottom.css("height",usefulHeight);
				
				
			} else setTimeout(function(){checkHeight(el, height)}, 100);
		}
		checkHeight(el, height);
		
		/* actions for the social media widget */
		jQuery(el)
			.find("#lu_sm_top")
				.find(".lu_sm_button")
					.unbind("click").click(function() {		/* switching different accounts */
						if(!jQuery(this).hasClass("lu_sm_active")) {
							var $newPanel = jQuery(this).parent().siblings("#lu_sm_bottom").find("#" + jQuery(this).attr("id") + "_content");
							var $currPanel = jQuery(this).parent().siblings("#lu_sm_bottom").find(".lu_sm_active");
							
							if($newPanel.length > 0 && $currPanel.length > 0) {
								jQuery(this)
									.siblings(".lu_sm_active").removeClass("lu_sm_active").end()
									.addClass("lu_sm_active");
								
								$newPanel.addClass("lu_sm_active");
								$currPanel.stop().removeClass("lu_sm_active")
									.animate({ "opacity": 0 }, 300, function() {
										jQuery(this).hide();
										$newPanel.stop().css({ "opacity": 0 }).show().animate({ "opacity": 1 }, 300);
									});
							}
						}
					})
				.end()
			.end()
		.end();
		
		
		var strErrorA = "<div class='lu_sm_feed'><div class='lu_sm_message'>";
		var strErrorB = "Error retrieving feeds...please try again</div></div>";
		var strErrorC = "No feed found";
		
		jQuery.ajax({
			type: "POST",
			url: "/templates/widgets/socialmedia/dsp_feeds.cfm",
			context: el,
			data: {
				fb: fb,
				tw: tw
			},
			error: function(xhr, desc, exceptionobj) {
				var strError = strErrorA + "(1) " + strErrorB;
				jQuery(el).find(".lu_sm_content").html(strError + xhr.statusText);
			},
			success: function(cfmResponse) {
				try {

					//jQuery('body').prepend("<div id='tDiv'></div>");
					//jQuery('#tDiv').html(cfmResponse);
					var responseObj = JSON.parse(cfmResponse);
					
					//var responseObj = JSON.parse(jsmin('',cfmResponse,3));
					
					if(responseObj.type == "Success") {
						if(responseObj.fb != "") {
							jQuery(el).find("#lu_sm_facebook_content").html(responseObj.fb);
						} else jQuery(el).find("#lu_sm_facebook_content").html(strErrorC);
						
						if(responseObj.tw != "") {
							jQuery(el).find("#lu_sm_twitter_content").html(responseObj.tw);
							
						} else jQuery(el).find("#lu_sm_twitter_content").html(strErrorC);
						
						
						if(responseObj.all != "") {
							jQuery(el).find("#lu_sm_all_content").html(responseObj.all);
						} else jQuery(el).find("#lu_sm_all_content").html(strErrorC);
					} else jQuery(el).find(".lu_sm_content").html(strErrorB);
				} catch(err) {
					
					strError = strErrorA + "(2) " + strErrorB;

					//strError = cfmResponse;
					jQuery(el).find(".lu_sm_content").html(strError);
				}
				
			}
		});
		
		
	}
};



/* initialization functions
 * you should only be adding key/classpath to the validTags (key corresponding to the tag used, classpath corresponding to a class above */
LU = {
	validTags: [
		{key: 'socialmedia', classpath: LU.LUML.SocialMedia}
	],

	init: function(e) {
		LU.Helper.jQueryInit();
	},
	
	parseDomTree : function(context) {
		for (var i=0; i<this.validTags.length; i++) {
			var $elements = context.find("#lu\\:"+ this.validTags[i]['key']);
			
			$elements
				.each(function() {
					LU.validTags[i]['classpath'](jQuery(this));
				})
			.end();
		}
	}
};



/* Helper functions for the Widget API 
 * any utilities used should go in here */
var lu_jquery_loaded = false;
LU.Helper = {
	jQueryInit: function() {
		if(typeof(jQuery) == 'undefined') {
			if(!lu_jquery_loaded) {
				lu_jquery_loaded = true;
				document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js\"></scr" + "ipt>");
			}
			setTimeout("LU.Helper.jQueryInit()", 50);
		} else {
			LU.parseDomTree(jQuery(document));
		}
	},
	
	getParams: function() {
		var el;
		var params = new Array();
		var tempParam = "";
		
		for(var i=0; i<arguments.length; i++) {
			if(i == 0) el = arguments[i];
			else {
				tempParam = "";
				tempParam = jQuery(el).attr(arguments[i]);
				if(tempParam != null) params[arguments[i]] = tempParam;
			}
		}
		
		return params;
	}
};

/* JSON Parsing script */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('3(!h.m){h.m={}}(5(){5 f(n){7 n<10?\'0\'+n:n}3(6 V.q.p!==\'5\'){V.q.p=5(a){7 W(h.X())?h.1q()+\'-\'+f(h.1r()+1)+\'-\'+f(h.1s())+\'T\'+f(h.1t())+\':\'+f(h.1u())+\':\'+f(h.1v())+\'Z\':w};G.q.p=1w.q.p=1x.q.p=5(a){7 h.X()}}x e=/[\\1y\\Y\\11-\\12\\13\\14\\15\\17-\\18\\19-\\1a\\1b-\\1c\\1d\\1e-\\1f]/g,H=/[\\\\\\"\\1z-\\1A\\1B-\\1C\\Y\\11-\\12\\13\\14\\15\\17-\\18\\19-\\1a\\1b-\\1c\\1d\\1e-\\1f]/g,8,z,1g={\'\\b\':\'\\\\b\',\'\\t\':\'\\\\t\',\'\\n\':\'\\\\n\',\'\\f\':\'\\\\f\',\'\\r\':\'\\\\r\',\'"\':\'\\\\"\',\'\\\\\':\'\\\\\\\\\'},o;5 I(b){H.1h=0;7 H.M(b)?\'"\'+b.A(H,5(a){x c=1g[a];7 6 c===\'J\'?c:\'\\\\u\'+(\'1i\'+a.1j(0).N(16)).1k(-4)})+\'"\':\'"\'+b+\'"\'}5 B(a,b){x i,k,v,l,C=8,9,2=b[a];3(2&&6 2===\'y\'&&6 2.p===\'5\'){2=2.p(a)}3(6 o===\'5\'){2=o.K(b,a,2)}1D(6 2){D\'J\':7 I(2);D\'O\':7 W(2)?G(2):\'w\';D\'1E\':D\'w\':7 G(2);D\'y\':3(!2){7\'w\'}8+=z;9=[];3(P.q.N.1F(2)===\'[y 1G]\'){l=2.l;E(i=0;i<l;i+=1){9[i]=B(i,2)||\'w\'}v=9.l===0?\'[]\':8?\'[\\n\'+8+9.L(\',\\n\'+8)+\'\\n\'+C+\']\':\'[\'+9.L(\',\')+\']\';8=C;7 v}3(o&&6 o===\'y\'){l=o.l;E(i=0;i<l;i+=1){k=o[i];3(6 k===\'J\'){v=B(k,2);3(v){9.1l(I(k)+(8?\': \':\':\')+v)}}}}Q{E(k 1m 2){3(P.1n.K(2,k)){v=B(k,2);3(v){9.1l(I(k)+(8?\': \':\':\')+v)}}}}v=9.l===0?\'{}\':8?\'{\\n\'+8+9.L(\',\\n\'+8)+\'\\n\'+C+\'}\':\'{\'+9.L(\',\')+\'}\';8=C;7 v}}3(6 m.R!==\'5\'){m.R=5(a,b,c){x i;8=\'\';z=\'\';3(6 c===\'O\'){E(i=0;i<c;i+=1){z+=\' \'}}Q 3(6 c===\'J\'){z=c}o=b;3(b&&6 b!==\'5\'&&(6 b!==\'y\'||6 b.l!==\'O\')){1o 1p 1H(\'m.R\');}7 B(\'\',{\'\':a})}}3(6 m.S!==\'5\'){m.S=5(c,d){x j;5 U(a,b){x k,v,2=a[b];3(2&&6 2===\'y\'){E(k 1m 2){3(P.1n.K(2,k)){v=U(2,k);3(v!==1I){2[k]=v}Q{1J 2[k]}}}}7 d.K(a,b,2)}c=G(c);e.1h=0;3(e.M(c)){c=c.A(e,5(a){7\'\\\\u\'+(\'1i\'+a.1j(0).N(16)).1k(-4)})}3(/^[\\],:{}\\s]*$/.M(c.A(/\\\\(?:["\\\\\\/1K]|u[0-1L-1M-F]{4})/g,\'@\').A(/"[^"\\\\\\n\\r]*"|1N|1O|w|-?\\d+(?:\\.\\d*)?(?:[1P][+\\-]?\\d+)?/g,\']\').A(/(?:^|:|,)(?:\\s*\\[)+/g,\'\'))){j=1Q(\'(\'+c+\')\');7 6 d===\'5\'?U({\'\':j},\'\'):j}1o 1p 1R(\'m.S\');}}}());',62,116,'||value|if||function|typeof|return|gap|partial||||||||this||||length|JSON||rep|toJSON|prototype||||||null|var|object|indent|replace|str|mind|case|for||String|escapable|quote|string|call|join|test|toString|number|Object|else|stringify|parse||walk|Date|isFinite|valueOf|u00ad|||u0600|u0604|u070f|u17b4|u17b5||u200c|u200f|u2028|u202f|u2060|u206f|ufeff|ufff0|uffff|meta|lastIndex|0000|charCodeAt|slice|push|in|hasOwnProperty|throw|new|getUTCFullYear|getUTCMonth|getUTCDate|getUTCHours|getUTCMinutes|getUTCSeconds|Number|Boolean|u0000|x00|x1f|x7f|x9f|switch|boolean|apply|Array|Error|undefined|delete|bfnrt|9a|fA|true|false|eE|eval|SyntaxError'.split('|'),0,{}))
