/*
* Marquee (VSee.com)
* 19 Dec 2009
* by Lionel Chan (chaoszcat@gmail.com)
*
* Description:
* A simple class that pull organization data from a text file, and render it out
* in the home page of VSee.com
*/
var Marquee = {
	
	file: '/js/organizations.txt',
	
	/*
	* Public
	* render out the Marquee into specified element id
	*/
	render: function(elem) {
		this.fetchCompanies();
		if (typeof elem == 'string') this.parentElem = $('#'+elem);
		if (typeof elem == 'object') this.parentElem = elem;
	},
	
	
	
	/*
	* Private
	* holds companies tuples
	*/
	data: [],
	
	/*
	* Private
	* parent element to hold the organizations
	*/
	parentElem: null,
	
	/*
	* Private
	* Simple bubble sort algorithm to sort companies in descending order
	*/
	sort: function(d) {
		var hasSwapped = false;
		do {
			hasSwapped = false;
			for (var i = 1; i < d.length; i++) {
				if (d[i-1].weight < d[i].weight) {
					var temp = d[i-1];
					d[i-1] = d[i];
					d[i] = temp;
					hasSwapped = true;
				}
			}
		}while (hasSwapped);
		return d;
	},
	
	duplicate: function(d) {
		var newArray = d;
		$.each(d, function(i, o) {
			if (o.weight > 1) {
				for (var k=0; k<o.weight;k++) {
					newArray.push(o);
				}				
			}	

		});
		return newArray;
	},
	
	randOrd : function() {
		return (Math.round(Math.random())-0.5);
	},
	
	randomize: function(d) {
		d.sort( Marquee.randOrd );
		return d;
	},
	
	/*
	* Private
	* fetch companies from the text file specified in line 4
	*/
	fetchCompanies: function() {
		$.get(Marquee.file, function(data){
			var sp = data.split("\n");
			var d = [];
			$.each(sp, function(i, o) {
				//Skip comments, empty line, illegal lines
				if (o.match(/^#/) || o == '') return true;
				var sp2 = o.split(",");
				d.push(
					{name: $.trim(sp2[0]), weight: parseInt($.trim(sp2[1]))}
				);
			});
						
			//Randomize the data
			//d = Marquee.duplicate(d);
			d = Marquee.randomize(d);
			
			//IE hang.. so choose only first 60 data
			d = d.slice(0, 60);
			
			//Rendering out!
			$.each(d, function(i, o) {
				var span = $(document.createElement('span'));
				span.html(o.name);
				Marquee.parentElem.append(span);
			});
			
			$('#organization').marquee().mouseenter(function() {
				$(this).trigger('stop');
			}).mouseleave(function() {
				$(this).trigger('start');
			});
		});
	}
};

$(document).ready(function() {
	Marquee.render('organization');
});
