// !Embed
pf.ui.embed = {

	init: function() {
	
		// initialize embed show/hide button
		Y.purgeElement("embed-link-frame");
		Y.addListener("embed-link-frame", "click", pf.ui.toggler.events);	
		
		// attach extra event listener to perform extra actions when embed panel is opened 
		Y.addListener("embed-link-frame", "click", pf.ui.embed.events);

		// set/update embed codes
		if ($("input[name='embed-type']:checked", '#embed-buttons').attr("id") == "embed-radio-html") {
			$("#embed-code-iframe").val(pf.ui.embed.html_src());
		} else {
			$("#embed-code-iframe").val(pf.ui.embed.iframe_src());		
		}

		// attach event listener for table width dropdown
		$("#embed-frame").bind("change", pf.ui.embed.events);
		
		$("#embed-code-html, #embed-code-iframe").bind("click", pf.ui.embed.events);

		
		// attach event listener for html preview link
		$("#html-preview-link").bind("click", pf.ui.embed.html_preview);
				
	},
	
	// generates the code for embedding tables via iframe
	iframe_src: function() {
		
		// get the selected table width from the width dropdown in the embed panel
		var width = $("#embed-width").val();
		width != "inherit" ? width = parseInt(width) : "";
		
		var src = "";
		// src += "<!-- Beginning of Playerfilter embed code -->\n"
		src += '<iframe scrolling="no" frameborder="0"';
		if (width != "inherit") { 
			src += ' width="' + width + '" ';
		}
		// $ style="width:';
		// src += $("#datatable-frame")height:';
		src += ' height="' + $("#datatable-frame").height() + '" ';
		src += 'src="http://playerfilter.com/embed/';
		src += pf.qs.split("/ws/nfl/players?query=")[1];
		src += '" style="margin:10px 0"/></iframe>\n';
		src += '<div style="font-size: 95%;margin:0 0 5px 0">Source: <a href="http://www.playerfilter.com">Playerfilter</a>.</div>';
		// src += "<!-- End of Playerfilter embed code -->"
		
		return src;
	
	},
	
	html_src: function() {
	
		var src = "";
		// src += "<!-- Begin Playerfilter table code -->\n";

		if (typeof(pf.screen.criteria) != "undefined") {
			
			// base css for th
			th_css = "background:#eee;padding:6px 3px 3px 3px;font-size:85%;vertical-align:bottom;";
			
			// src += "<div style=\"width:" + $("#embed-width").val() + "px;overflow:hidden\">";
			src += "<table width=\"" + $("#embed-width").val() + "\" style=\"font-size: 95% !important;color:#333;border-spacing:0 !important;overflow:hidden\"><thead>";
			src += '<tr>';
			
			// rank 
			src += "<th style=\"" + th_css + "\"></th>";
			// player name
			src += "<th style=\"" + th_css + "\">Player</th>";
			// season column
			pf.screen.mode.type == "s" ? src += '<th style=\"' + th_css + '\">Season</td>' : "";
			// week column
			if (pf.screen.mode.type == "w") {
				src += '<th style=\"' + th_css + '\">Week</th>';
				src += '<th style=\"' + th_css + '\">Opp</th>';
				src += '<th style=\"' + th_css + '\">Score</th>';
			}

			// user-defined columns
			for (var i=0;i<pf.screen.criteria.length; i++) {
				c = pf.screen.criteria[i];
				if (!c.hidden) {
					// style the sorted column
					if (c.sort) {
						src += "<th style=\"" + th_css + "font-weight:bold;text-align:right;background:#dddddd;\">";					
					} else {
						src += "<th style=\"" + th_css + "text-align:right;\">";					
					}
					// column header label
					src +=  pf.ui.datatable.init.formatters.header_label(c);
					src += "</th>";
				} 
			}
			
			src += "</tr></thead><tbody>";

			// base css for td
			td_css = "padding:3px 3px 3px 3px;font-size:90%;white-space:pre;";
			
			// a bit of logic for how many results to render
			pf.screen.results.length > 30 ? result_limit = $("#embed-limit").val() : result_limit = pf.screen.results.length;				
			
			// results
			for (var i=0;i<result_limit; i++) {
				
				r = pf.screen.results[i];
				src += "<tr style=\"border-bottom: 1px solid #eee;margin-left:10px;\">";
				// rank column				
				src += "	<td style=\"" + td_css + "text-align:right;color:#ccc;\">" + (i+1) + "</td>";
				// player name
				src += "	<td style=\"" + td_css + "font-weight:bold;\">" + r["name"] + "</td>";
				
				// season/week
				pf.screen.mode.type == "s" ? src += '<td style="' + td_css + '">' + r["y"] + "</td>" : "";
				
				if (pf.screen.mode.type == "w") { 
					src += '<td style="' + td_css + '">' + r["w"] + "</td>";
					src += '<td style="' + td_css + '">' + r["o"] + "</td>";
					src += '<td style="' + td_css + '">' + r["s"] + "</td>";

				}
				
				// results
				for (var x=0; x<pf.screen.criteria.length; x++) {
					c = pf.screen.criteria[x];
					if (!c.hidden) {
						// style the sorted column
						if (c.sort) {
							src += '<td style="' + td_css + 'text-align:right;">' + r[x] + "</td>";
						} else {
							src += '<td style="' + td_css + 'text-align:right;">' + r[x] + "</td>";
						}
					} 
				}
				
				src += "</tr>";
				
			}
			
			
			// title and source
			src += '<tr><td colspan="100" style="padding:6px 0 10px;font-size:85%;color:#666;">Source: <a href="http://www.playerfilter.com" target="_blank">Playerfilter</a>.</td></tr>';

			src += '</tbody></table>';
			// src += '</div>';
			
			// src += "<!-- end Playerfilter table code -->";
			
			return src;
			
		}
		
	},
	
	// events related to the embed options
	events: function (e) {
		
		var div = Y.getTarget(e);
		
		// set/update embed codes
		if ($("input[name='embed-type']:checked", '#embed-buttons').attr("id") == "embed-radio-html") {
			$("#embed-code-iframe").val(pf.ui.embed.html_src());
		} else {
			$("#embed-code-iframe").val(pf.ui.embed.iframe_src());		
		}
		
		// $("#embed-code-iframe").val(pf.ui.embed.iframe_src());
		// $("#embed-code-html").val(pf.ui.embed.html_src());		
		
		// if width dropdown is being changed
		if (div.id == "embed-width" && e.type == "change") {
			
			// set the table width
			var width = $("#embed-width").val();
			width != "inherit" ? width = parseInt(width) : "";
			$("#datatable-frame").width(width);
			$("#datatable-frame").css("overflow", "hidden");
		
		// if limit dropdown is being changed 
		} else if (div.id == "embed-limit" && e.type == "change") {
		
			// set the limit in the newscreen and get the data
			var limit = $("#embed-limit").val();
			pf.newscreen.limit = limit;
			pf.js.getData(pf.newscreen);
		
		// if either iframe or html textarea is being clicked, automatically select text
		} else if ((div.id == "embed-code-iframe" || div.id == "embed-code-html") && e.type == "click") {			
			$(div).select();
			
		// if embed button is being clicked
		} else if ($(div).parent("#embed-link-frame") && e.type == "click") {
			
			// if the embed panel is being closed
			if (!$('#embed-frame').is(':visible')) {
				
				// clear embed settings 
				pf.ui.embed.clear();
			
			// if the embed panel is being opened
			} else {
				
				// set the table width
				var width = $("#embed-width").val();
				width != "inherit" ? width = parseInt(width) : "";
				$("#datatable-frame").width(width);
				$("#datatable-frame").css("overflow", "hidden");
				
				// set the limit and update the data
				var limit = $("#embed-limit").val();
				pf.newscreen.limit = limit;
				pf.js.getData(pf.newscreen);	
			
			}
		
		}
		
		// if the table width is higher than the selected width for embedding, provide an error
		if ($("#datatable-frame table").width() > $("#embed-width").val()) {

			// calculate the number of columns that are hidden			
			var hiddenCols = new Array();
			$("#datatable-frame table").find("th").each(function() {
				if ($(this).position().left > $("#embed-width").val())
					hiddenCols.push($(this));
			});
			
			// generate the error message
			error_str = "<h3>Please remove ";
			
			if (hiddenCols.length > 1) {
				error_str += hiddenCols.length + " columns";
			} else {
				error_str += "one column";
			}
			
			error_str += " or increase the table width before embedding.</h3>";
			
			// error some columns or increase the table width.</h3>";
			error_str += "This embedded table is " + $("#embed-width").val() + " pixels wide - ";
			// error_str += "Too many columns are selected: ";
			
			if (hiddenCols.length > 1) {
				error_str += hiddenCols.length + " columns do not fit and are hidden.";
			} else {
				error_str += "1 column does not fit and is hidden.";
			}
			
			error_str += "";
			
			$("#embed-errors").show();		
			$("#embed-errors").html(error_str);
			
			
		} else {

			$("#embed-errors").hide();
			$("#embed-errors").html("");
		
		}
		
	},
	
	// clear remnants of embed preview
	clear: function() {

		// reset the table width
		$("#datatable-frame").width("inherit");
		// get rid of the limit
		pf.newscreen.limit = false;
		// update the data
		pf.js.getData(pf.newscreen);
	
	},
	
	html_preview: function() {
	
		$.ajax({
			type: "POST",
			url: "embed/html-preview",
			data: { html_source: $("#embed-code-html").val() },
			success: show_preview,
			failure: function() {
				alert("html preview failed :(");
			}
		});
		
		function show_preview(data) {
		
			$.colorbox({html:data});
					
		}
	
	}
	
}


