//jQuery.noConflict(); // Safety first
var $j = jQuery;

window.div			=	'content';					// Main content DIV
window.key			=	'pq_jQhFesPXGhllNNgLXxYg';	// Spreadhseet for data
window.sheet 		= 	1;							// Tab in spreadsheet
window.type			=	'list';						// Value return type
window.storylimit 	= 	3;
window.story = getVar('story');
window.story = window.story.toLowerCase();
if (window.story == '') {
	window.story = 'home'
}

window.sidebar	=	'\
		<td width="288" align="left" valign="top" id="sidebar">\
			<div class="wrap">\
				<a href="http://ww1.fsafood.com/fsavideo/AYS_VideoFeed.aspx?name=SSA Company" target="_blank" class="video">\
					<img class="arrow"src="lib/img/videoarrow.gif" />\
					<span>See what sets SSA apart</span>\
				</a>\
				<div id="inthenews">\
					Loading...\
				</div>\
			</div>\
		</td>';
		
window.newshead =	'<h1>&quot;IN THE NEWS&quot;</h1>';

window.newsitem =	'\
		<a href="?story=#{story}" class="#{theclass}">\
			<h2>#{title}</h2>\
			<img src="lib/img/#{img}" />\
			<p>#{preview}</p>\
			<div class="readmore"><span class="date">#{date}</span><span class="rm">read more</span><div class="line"></div></div>\
		</a>';
		
window.newsfoot = '<a href="?story=all" class="archive">Visit the News Archive...</a>';



// If ?edit in the URI, forward to a login page for the google spreadsheet
if (getVar('edit')==1) {
	window.location = 'http://spreadsheets.google.com/ccc?key='+window.key;
}



$(document).ready(function(){
	if (window.home == 1) {
		displayResults();
	}
});


// Outputs Spreadsheet data to the DOM
function listEntries(json) {
	var div = $('#'+window.div);
	var first = 1;

	$('#content').parent().append(window.sidebar);
	var vals = {};
	
	for (var i = 0; i < json.feed.entry.length; i++) {
	    var entry = json.feed.entry[i];
    	vals.title = entry.gsx$title.$t;
		vals.date = entry.gsx$dateadded.$t;
		vals.img = entry.gsx$image.$t;
		vals.preview = entry.gsx$previewtext.$t;
		vals.content = entry.gsx$content.$t;
		vals.story = i;	
		vals.theclass = '';
		
		if (i <= window.storylimit && window.story != 'all') {
			if (window.story == vals.story) {
				div.html(vals.content);
				vals.theclass = 'active';
			}
			if (first == 1 && vals.title != '') {
				first = 0;	
				$('#inthenews').html(window.newshead);
			}
			if (vals.title != '') {
				vals.date = '';
				var item = $.tmpl(window.newsitem, vals);
				$('#inthenews').append(item);
			}		
		}
		
		if (window.story == 'all') {
			if (first == 1 && vals.title != '') {
				first = 0;	
				$('#sidebar').remove();
				
				var item = $.tmpl(window.newsitem, vals);
				div.attr({id: 'inthenews'}).addClass('wide');
				div.html(item);
			} else {
				var item = $.tmpl(window.newsitem, vals);
				$('#inthenews').append(item);
			}
			
		}
    }
    if (window.story != 'all') {
    	$('#inthenews').append(window.newsfoot);
    }
	sidebarStyling();
}


/**
 * Creates a new script element
 * in the DOM whose source is the JSON feed, 
 * and specifies that the callback function is 
 * 'listEntries' for a list feed and 'cellEntries' for a
 * cells feed (above).
 */
function displayResults() {
	
	var key 	= 	window.key;
	var sheet 	= 	window.sheet;
	var type	=	window.type;
	
	// Retrieve the JSON feed.
	var script = document.createElement('script');
	
	if (type == 'list') {
		script.setAttribute('src', 'http://spreadsheets.google.com/feeds/'
	         + type
	         + '/' + key
	         + '/' + sheet + '/public/values' +
	        '?alt=json-in-script&callback=listEntries&orderby=column:Date%20Added&reverse=true'); // Sort-by
	}
	
	if (type == 'cells') {
		script.setAttribute('src', 'http://spreadsheets.google.com/feeds/'
	         + type
	         + '/' + key
	         + '/' + sheet + '/public/values' +
	        '?alt=json-in-script&callback=cellEntries&return-empty=true');
	}
	
	script.setAttribute('id', 'jsonScript');
	script.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(script);;
}


function sidebarStyling(){
	// Sidebar Animations
	
	// Video arrow animation
	$("#sidebar").find('a.video').hoverIntent(function(){
			$(this).find('img.arrow').animate({left:10}, 500);
		}, function(){
			$(this).find('img.arrow').animate({left:0}, 500);
		})
		.find('img').animate({opacity: .8}, 0);
	
	// Fade out active news items
	$("#sidebar").find('a').each(function(){
		var url = $(this).attr('href');
		
		if (location.href.indexOf(url) != -1) {
			$(this).addClass('active').click(function(){
				return false;
			});
			
			if($.browser.msie){
				$(this).css({opacity:.5});
			}
		}
	});	

}


/**
 * Removes the script element from the previous result.
 */
function removeOldJSONScriptNodes() {
  var jsonScript = document.getElementById('jsonScript');
  if (jsonScript) {
    jsonScript.parentNode.removeChild(jsonScript);
  }
}

/**
 * Removes the output generated from the previous result.
 */
function removeOldResults() {
  var div = document.getElementById(window.div);
  div.innerHTML = '';
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function toProperCase(s) {
  return s.toLowerCase().replace(/^(.)|\s(.)/g, 
	  function($1) { return $1.toUpperCase(); });
}



// Javascript implimentation of PHP $_GET['var']... Modded to return 1 if value is mentioned at all immediately following ?
//	ie: ?edit will return edit = 1
function getVar(name) {
	get_string = document.location.search;         
	return_value = '';
	
	do { //This loop is made to catch all instances of any get variable.
		name_index = get_string.indexOf(name + '=');
		name_index2 = get_string.indexOf('?' + name);
		
		if(name_index != -1 || name_index2 != -1)
		{
			if (name == 'edit') { return 1 }
			
			get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);
			
			end_of_value = get_string.indexOf('&');
			if(end_of_value != -1)                
				value = get_string.substr(0, end_of_value);                
			else                
				value = get_string;                
			
			if(return_value == '' || value == '')
				return_value += value;
			else
				return_value += ', ' + value;
		}
	} while(name_index != -1)
		
	//Restores all the blank spaces.
	space = return_value.indexOf('+');
	while(space != -1)
	{ 
	return_value = return_value.substr(0, space) + ' ' + 
	return_value.substr(space + 1, return_value.length);
				 
	space = return_value.indexOf('+');
	}
	
	return(return_value);        
}

function log(msg) {
	if (console) {
		console.log(msg);
	} else if(window.console) {
		window.console.log(msg);
	} 
	else {
		alert(msg);
	}
}












//	DEPRECIATED



// Outputs Spreadsheet data to the DOM
//	function cellEntries(json) {
//		//console.log(json);
//		var div = $('#'+window.div);
//		var first = 1;
//		var rowlimit = 4;
//		//removeOldResults();
//	
//		$('#content').parent().append(window.sidebar);
//		
//		var vals = {};
//		
//		// Iterate through rows... Skip header 
//		for (var i= json.feed.gs$colCount.$t; i < json.feed.entry.length; i++) {
//			var entry = json.feed.entry[i];
//			var col =  entry.gs$cell.col * 1;
//			var row =  entry.gs$cell.row * 1;
//			
//		
//			switch(col) {
//				case 1: // Column 1: Title
//					vals.title = entry.content.$t;
//					break; 
//					
//				case 2:	// Column 2: Date
//					vals.date = entry.content.$t;
//					break;
//						   
//				case 3:	// Column 3: Image
//					vals.img = entry.content.$t;
//					break;
//				
//				case 4: // Column 4: Preview Text
//					vals.preview = entry.content.$t;	
//					
//					break;
//				
//				case 5:	// Column 5: Content
//					vals.story = row;
//					if (row <= rowlimit) {
//						if (window.story == vals.story) {
//							div.html(entry.content.$t);
//							
//							vals.theclass = "active";
//						}else {
//							 vals.theclass = "";
//						}
//						
//						if (first == 1 && vals.title != '') {
//							first = 0;	
//							$('#inthenews').html(window.newshead);
//						}
//						if (vals.title != '') {
//							var item = $.tmpl(window.newsitem, vals);
//							$('#inthenews').append(item);
//						}	
//						
//					}
//					break;
//			} 
//			
//		} 
//		
//		
//		sidebarStyling();
//	}


//	function film_num(){
//		
//		var i = 0;
//		for (i=0;i<=2;i++) {
//			var dis = $('#sidebar div a.video ul').find('li:eq('+i+')');
//			if (window.frame <= 6) {			
//				var o = rand(40,50)/100;	// opacity
//				o += ( (1/(4-i))*20 ) / 100;
//				dis.css({opacity: o});
//			} else {
//				
//				var val = dis.html();
//				val = parseInt(val)-1;
//				if (val <= 0) val = 9;
//				dis.html(val);
//			}	
//		}
//		
//		if (window.frame <= 6) { window.frame += 1; } else {window.frame = 0;}
//	
//		if (window.numbers) {
//			setTimeout(film_num, 100);
//		}
//		
//	}
//	
//	function filmover(){
//		$(this).find('ul, img').animate({opacity: 1}, 300);
//		
//		var id = $(this).attr('id');
//		window.numbers = true;
//		film_num();
//	}
//	
//	function filmout() {
//		$(this).find('ul, img').animate({opacity: .7}, 300, function(){
//			window.numbers = false;
//		});
//		
//	
//	}
//	
//	
//	function rand( min, max ) {
//	    // http://kevin.vanzonneveld.net
//	    // +   original by: Leslie Hoare
//	    // +   bugfixed by: Onno Marsman
//	    // *     example 1: rand(1, 1);
//	    // *     returns 1: 1
//	    var argc = arguments.length;
//	    if (argc == 0) {
//	        min = 0;
//	        max = 2147483647;
//	    } else if (argc == 1) {
//	        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
//	    }
//	    return Math.floor(Math.random() * (max - min + 1)) + min;
//	}