/************************************************/
/* Benchmark Graph Plugin            	        */
/* Created By Brandon Drake  			        */
/* Version: 1.1     				            */
/*						                        */	
/* Requires jquery.jcarousel.min.js		        */
/************************************************/

(function($) {
	$.fn.graph = function (options) {
	    	
		var defaults = {
			columns: 6,								// Number of viewable thumbnails
			imgHeight: 50,							// jCarousel slider image height
			imgWidth: 75,							// jCarousel slider image width
			jsonScript: '',							// JSON return file './scripts/json/benchmark.js' anything that will return a JSON object can be used
			jsonObject: null,						// JSON Object. Overrides jsonScript
			ajaxData: {},							// Data array to pass to the AJAX call
			cssClass: 'jcarousel-skin-benchmark',	// jCarousel css skin to use
			imgEvent: 'click',						// 'click' or 'mouseenter'
			afterEvent: $.noop,						// Additional call added to the image event
			animate: true,							// Turns off animation
			jCarouselEnabled: true					// Use jCarousel
		};

        /**
         * Determins the interval max so that we have a relatively useful
         * scale to put our visualizations on.
         */
		function getIntervalMax(max) {
			var multiplier = 1;			
			if (max >= 90 && max <= 999) {
				multiplier = 10;
			} else if (max >= 1000 && max <= 9999) {
				multiplier = 100;
			} else if (max >= 10000 && max <= 99999) {
				multiplier = 1000;
			} else if (max >= 100000 && max <= 999999) {
				multiplier = 10000;
			}			
			max = parseInt(max / multiplier, 0) + 10;			
			while (max % 6 != 0) {
				max += 1;
			}			
			return max * multiplier;
		}
		
        /**
         *  Draws and animates the benchmark results
         */
		function drawGraph(data,dataxis) {
			var graph = $("#" + objID + " .graphs"),
			caption = $("#" + objID + " .graph_desc"),
            compare = $("#" + objID + " .compare"),
			width = graph.width(),
			values = data.results,
			ct = values.length,
			i,
			drawWidth = 0,
			max = Math.max.apply(null, values),
			scale = getIntervalMax(max),
			temp = 0,
			scaleMax = (7 * scale) / 6;
			
			caption.find("h2").html(unescape(data.name));
			compare.html(data.subscript);
			
			for(i = 1; i < dataxis.length; i += 1) {
			    var p_update = (dataxis[i].url == "") ? unescape(dataxis[i].name) :
			        dataxis[i].rank + " <a href='" + dataxis[i].url + "'>" +
                    unescape(dataxis[i].name) + "</a>";			    
			    $("#title_"+ i +"").find("p").html(p_update);
			}
			  
			for (i = 0; i < ct; i += 1) {
			    // first bar if not ranked
			    if(i == 0) {
			        if(parseInt(values[i]) == 0) {
			            $(".row_first").addClass("none");
			            $(".row_first").html("Not Yet Rated. If You Are A "+ dataxis[0].name +" Representative & Wish To Be Rated, <a href=\"http://www.topseos.com/rankings/search-engine-marketing-agencies/apply-for-ranking\" title=\"Click Here\">Click Here</a>");
			        } else {
			            $(".row_first").removeClass("none");
			            var lwidth = Math.round( (values[i] / scaleMax) * width );
			            $(".row_first").html("<div class=\"bar first_bar\" id=\"graph_graph_0\" style=\"width: " + lwidth + "px;\">" + 
			                "</div><div class=\"value\" id=\"graph_graph_0_value\">" + parseInt(values[i]) + "</div>");
			        }
			    }
			    
				drawWidth = Math.round( (values[i] / scaleMax) * width );
				var bar = $("#" + objID + "_graph_" + i.toString());

				if (options.animate === true) {
				    // Perform animations
					bar.stop(true, false).animate({ width: drawWidth }, {
						duration: 500, 
						complete: function () {
							 temp += 1;
		
							// afterEvent call when animation is on
							if (temp === (ct)) {
								if (initLoad === false) {
									options.afterEvent.call();                                      
								} else {
									initLoad = false;
								}
							} 
						}
					});
				} else {
					bar.width(drawWidth);
				}
                
                var value = (values[i] <= -1) ? "[Not Tested]" : values[i];			
			    var valuetype = typeof value;			    
			    if (valuetype == 'number') {				
					value += '';
					x = value.split('.');
					x1 = x[0];
					x2 = x.length > 1 ? '.' + x[1] : '';
					var rgx = /(\d+)(\d{3})/;
					while (rgx.test(x1)) {
					  x1 = x1.replace(rgx, '$1' + ',' + '$2');
					}
					value = x1 + x2;				
			    }

			    $("#" + objID + "_graph_" + i.toString() + "_value").html(value);		    
			}

			// afterEvent call when animation is off
			if (options.animate === false) {
                options.afterEvent.call();
			}
			
			// Set the scale values
			for (i = 6; i >= 0; i -= 1) {
			    $("#" + objID + "_grid_base_" + i.toString()).html("&nbsp;" + (scale / 6)  * i);
			}
		}
		
		function processAjax() {			
			$.ajax({
				url: options.jsonScript,
				type: 'GET',
				cache: false,
				data: options.ajaxData,
				dataType: 'json',
				success: function (data) {
					getData(data);
				}
			});
		}

        /*
         * Gets the JSON object, parses it, builds the graph, 
         * and attaches the data values onto the thumb nails.
         */
		function getData(data) {
			var ml = data.metrics.length;
			var i;
			var graph_nav = "";
			var nav_tabs = "";
            var graph_rows = "";
			var graph_body = "";
            
            // tabs
			for (i = 0; i < ml; i++) {
				var navClass = (i === 0) ? "graph_nav_tab_selected" : "";
				nav_tabs += "<div><div class='graph_nav_tab " + navClass + "' index='"+i+"'>" + 
				                unescape(data.metrics[i].name) + "</div></div>\n";
			}
			
			graph_nav += "<div class='graph_nav'>\n" +
								"<h3>View Comparison Chart For Service:</h3>\n" +
                                "<div class='graph_nav_scrollable'>\n" +
                                    "<div class='graph_nav_items'>\n" +
                                        nav_tabs +
                                    "</div>\n" +
                                "</div>\n" +
							"</div>\n" ;							
			
			var ax0 = data.axis[0].c.length;
			for (i = 1; i < ax0; i += 1) {				
                rowClass = (i === (ax0-1)) ? " last_bar" : "";
				graph_rows += "<div class='title' id='title_"+ i +"'><div class='title_wrapper'>";
                graph_rows += (data.axis[0].c[i].url == "") ? "<p>"+unescape(data.axis[0].c[i].name)+"</p>" : "<p>" +
                                    data.axis[0].c[i].rank + " <a href='" + data.axis[0].c[i].url + "'>" +
                                    unescape(data.axis[0].c[i].name) + "</a></p>";
                graph_rows += "</div></div>\n" +
                                "<div class='row'>\n" +
                                    "<div id='" + objID + "_graph_" + i + "' class='bar" + rowClass + "'></div>\n" +
                                    "<div id='" + objID + "_graph_" + i + "_value' class='value'></div>\n" +
                                "</div>\n";
			}
			
			graph_body += "<div class='graph_body'>\n" +
                                "<div class='graph_content'>\n" +
                                    "<div class='graphs'>\n" +
                                        "<div class='title'><div class='title_wrapper'>";

            graph_body += (data.axis[0].c[0].url == "") ? "<p>"+unescape(data.axis[0].c[0].name)+"</p>" : 
                                "<p><a href='" + data.axis[0].c[0].url + "'>" + unescape(data.axis[0].c[0].name) + "</a></p>";
                                                            
            graph_body +=               "</div></div>\n" +
                                        "<div class='row row_first'>\n" +
                                            "<div id='" + objID + "_graph_0' class='bar first_bar'></div>\n" +
                                            "<div id='" + objID + "_graph_0_value' class='value'></div>\n" +
                                        "</div>\n" +
                                        "<div class='compare'></div>\n" +
                                        graph_rows +
                                    "</div>\n" +
                                "</div>\n" +
                            "</div>\n";
			
			graph_html = graph_nav + graph_body;
			obj.html(graph_html);
			drawGraph(data.metrics[0],data.axis[0].c);
            
            $('.graph_nav_tab').live('click', function(){
				var index = $(this).attr("index");
				drawGraph(data.metrics[index],data.axis[index].c);
				$('.graph_nav_tab').removeClass('graph_nav_tab_selected');
				$(this).addClass('graph_nav_tab_selected');                
			});
		}
		
		var options = $.extend(defaults, options), // override the default options with the user defined options
			obj = $(this),
			objID = obj.attr('id'),
            initLoad = true;
		
		if (options.jsonObject === null) {
			processAjax();
		} else {
			getData(options.jsonObject);
		}
	}
})(jQuery)

