$(function(){
	// removes background and padding on last menu item
	$('#top_nav ul li:last,footer ul li:last').css({'background':'none','padding':0});
	
	// equal heights for apps
	$('.apps,.equal').equalheights({
		offset: -5
	});
	
	// call to load brands enabled and audiences served count
	if ($('#landing').length) {
		$.getJSON('http://www.involver.com/analytics/stats?callback=?', function(data){
			clearInterval(jsonError);
			$('#brands_enabled p').text(addCommas(data.brands));
			$('#audience_served p').text(addCommas(data.audience));
		});
		jsonError = setInterval(function() {
			$('#brands_enabled p').text('105,912');
			$('#audience_served p').text('504,520,538');
		},2500);
	}
	
	// homepage slideshow
	$('#feature').faded({
		speed: 500,
		crossfade: false,
		loading: true,
		loadingimg: '/img/feature-loading.gif',
		autoplay: 3500,
		autorestart: 3500,
		autopagination:false,
		completeCycle: function() {
			$("#quotes div").click();
		}
	});
	
	// in the news delicious feed
	$.getJSON("http://feeds.delicious.com/v2/json/involver_marketing?count=5amp;callback=?", function(data) {
		$.each(data, function(i,item){
			var date = item.dt.split('T');
			var html = '<li><small>' + date[0] + '</small><br><a href="' + item.u + '" target="_blank">' + item.d + '</a></li>';
			$(html).appendTo("#in_the_news ul");
        });
	});
	
	// rotating quotes on homepage
	$("#landing #quotes").faded({
		speed: 800,
		autoheight: 250,
		autopagination:false,
		random: true,
		bigtarget:true
	});
	
	// rotating quotes on contact
	$("#contact #quotes").faded({
		speed: 800,
		autoheight: 250,
		autopagination:false,
		autoplay: 16800,
		random: true,
		bigtarget:true
	});
	
	$.metadata.setType("attr", "validate");
	$("#form18").validate();
	
	// fake click for thumbnails
	$('.app .tn').click(function(e){
		e.preventDefault();
		$(this).find('.zoom').click();
	});
	
	// lightbox class for contact us
	$('.lightbox').click(function(e){
		e.preventDefault();
		var src = '/eloqua/' + $(this).attr('href').replace('#','') + '.html';
		$("#frame iframe").attr('src',src);
		$('#frame').lightbox_me({
			centered: true,
			overlaySpeed: 0,
			overlayCSS: {background :'url(/img/overlay.png) repeat'}
	     });
	});

	// lightbox for expanded app view
	$('.feature .zoom,.app .zoom').click(function() {
		var imgName = $(this).attr('href').replace('#','');
		var lightBox = $("<div/>", {
		    id: imgName,
		 	className: 'lb',
		    html: $("<div/>", {
		        className: 'lb_header',
				html: $("<img/>", {
			        src: '/img/lb_involver.png',
					className: 'lb_involver'
			    })
		    })
		});
		
		var content;
		if ($(this).parents('div.app').find('.description').length) {
			content = '<h1>' + $(this).parents('div.app').find('.content h1').html() + '</h1>';
			content += $(this).parents('div.app').find('.description').html();
			if ($(this).parents('div.app').find('.fb_install').length) {
				content += '<a href="'+ $(this).parents('div.app').find('.content a.fb_install').attr('href') +'" class="'+ $(this).parents('div.app').find('.content a.fb_install').attr('class') +'">' + $(this).parents('div.app').find('.content a.fb_install').html() + '</a>';
			}
			if ($(this).parents('div.app').find('.contact_us').length) {
				content += '<a href="/contact/" class="btn contact_us lightbox">Contact Us</a>';
			}
		} else {
			content = $(this).parents('div.app').find('.content').html();	
		}

		var close = $('<a/>', {
	        href: '#',
			className: 'close',
			html: $('<img/>', {
				src: '/img/lb_close.png'
			})
	    });
		
		if ($('div#' + imgName).length) {
			$('#' + imgName).lightbox_me({
		        centered: true,
				overlaySpeed: 0,
				overlayCSS: {background :'url(/img/overlay.png) repeat'}
		     });
		} else {
			$(lightBox).lightbox_me({
				centered: true,
				overlaySpeed: 0,
				overlayCSS: {background :'url(/img/overlay.png) repeat'},
		        onLoad: function() {
					$(close).appendTo('#' + imgName + ' .lb_header');
		           	$('<img/>', {
						src: '/img/lb_screenshot.png',
						css: { display: "none" },
						className: 'image'
					}).appendTo('#' + imgName);
					
					$('<div/>', {
						className: 'content',
						style: 'display:none',
						html: content
					}).appendTo('#' + imgName);
					
					var loadImg = '/img/app-' + imgName + '.jpg' + "?" + (new Date()).getTime();
					$('#' + imgName + " img.image").attr("src", loadImg).load(function() {
						$(this).fadeIn(300);
						$('#' + imgName + " .content").fadeIn(300);
					});
		     	}
		     });
		}
		
		// points contact href to /contact/
		$('.lb a.contact_us').attr('href','/contact/');
	    
	    return false;
	});
	
	if ($('#applications').length) {
		var app = getQuery('app');
		if ($('.app.' + app).length) {
			$('.app.' + app + ' .zoom').click();
		}
	}
	
	// submits /contact/ form
	$('.send_message').click(function(){
		$(this).parent().submit();
		return false;
	});
	
});

function getQuery(obj) { 
	var string = window.location.search.substring(1); 
	var strings = string.split('&'); 
	for (var i=0; i < strings.length; i++) { 
		var set = strings[i].split('='); 
		if (set[0] == obj) { 
			return set[1];
		} 
	} 
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.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');
	}
	return x1 + x2;
}

/*
CSS Browser Selector v0.3.5 (Feb 05, 2010)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

/**
 * Plugin: jquery.zRSSFeed
 * 
 * Version: 1.1.2
 * (c) Copyright 2010-2011, Zazar Ltd
 * 
 * Description: jQuery plugin for display of RSS feeds via Google Feed API
 *              (Based on original plugin jGFeed by jQuery HowTo. Filesize function by Cary Dunn.)
 * 
 * History:
 * 1.1.2 - Added user callback function due to issue with ajaxStop after jQuery 1.4.2
 * 1.1.1 - Correction to null xml entries and support for media with jQuery < 1.5
 * 1.1.0 - Added support for media in enclosure tags
 * 1.0.3 - Added feed link target
 * 1.0.2 - Fixed issue with GET parameters (Seb Dangerfield) and SSL option
 * 1.0.1 - Corrected issue with multiple instances
 *
 **/

(function($){

	$.fn.rssfeed = function(url, options, fn) {	
	
		// Set plugin defaults
		var defaults = {
			limit: 10,
			header: true,
			titletag: 'h4',
			date: true,
			content: true,
			snippet: true,
			showerror: true,
			errormsg: '',
			key: null,
			ssl: false,
			linktarget: '_self'
		};  
		var options = $.extend(defaults, options); 
		
		// Functions
		return this.each(function(i, e) {
			var $e = $(e);
			var s = '';

			// Check for SSL protocol
			if (options.ssl) s = 's';
			
			// Add feed class to user div
			if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
			
			// Check for valid url
			if(url == null) return false;
			
			// Create Google Feed API address
			var api = "http"+ s +"://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(url);
			if (options.limit != null) api += "&num=" + options.limit;
			if (options.key != null) api += "&key=" + options.key;
			api += "&output=json_xml"

			// Send request
			$.getJSON(api, function(data){
				// Check for error
				if (data.responseStatus == 200) {
	
					// Process the feeds
					_process(e, data.responseData, options);

					// Optional user callback function
					if ($.isFunction(fn)) fn.call(this,$e);
					
				} else {

					// Handle error if required
					if (options.showerror)
						if (options.errormsg != '') {
							var msg = options.errormsg;
						} else {
							var msg = data.responseDetails;
						};
						$(e).html('<div class="rssError"><p>'+ msg +'</p></div>');
				};
			});				
		});
	};
	
	// Function to create HTML result
	var _process = function(e, data, options) {

		// Get JSON feed data
		var feeds = data.feed;
		if (!feeds) {
			return false;
		}
		var html = '';	
		var row = 'odd';
		
		// Get XML data for media (parseXML not used as requires 1.5+)
		var xml = getXMLDocument(data.xmlString);
		var xmlEntries = xml.getElementsByTagName('item');

		$("<div>",{
			"class":"rssBody"
		}).appendTo(e);
		
		for (var i=0; i<feeds.entries.length; i++) {
			// Get individual feed
			var entry = feeds.entries[i];

			if ( !$( "ul#category_" + entry.categories[0].split(' ').join('_')).length ) {	
				$("<ul>",{
					id: "category_" + entry.categories[0].split(' ').join('_')
				}).appendTo(".rssBody");
				console.log(entry.categories[0]);	
				$("<h4>",{
					text: entry.categories[0]
				}).insertBefore("#category_" + entry.categories[0].split(' ').join('_'));
			}
			
			// Format published date
			var entryDate = new Date(entry.publishedDate);
			var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
				
			$("<li>",{
				"class": "rssRow " + row,
				html: '<'+ options.titletag +'><a href="'+ entry.link +'" title="View this feed at '+ feeds.title +'" target="'+ options.linktarget +'">'+ entry.title +' (' + entry.categories[1] + ')</a></'+ options.titletag +'>'
			}).appendTo("ul#category_" + entry.categories[0].split(' ').join('_'));
		};		
		
/*
		// Add body
		html += '<div class="rssBody">' +
			'<ul>';
		
		// Add feeds
		for (var i=0; i<feeds.entries.length; i++) {
			
			// Get individual feed
			var entry = feeds.entries[i];
		
			// Format published date
			var entryDate = new Date(entry.publishedDate);
			var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
			
			// Add feed row
			html += '<li class="rssRow '+row+'">' + 
				'<'+ options.titletag +'><a href="'+ entry.link +'" title="View this feed at '+ feeds.title +'" target="'+ options.linktarget +'">'+ entry.title +'</a></'+ options.titletag +'>'
				
			html += "<p>" + entry.categories[0] + "</p>";
			 
			if (options.date) html += '<div>'+ pubDate +'</div>'
			if (options.content) {
				
				// Use feed snippet if available and optioned
				if (options.snippet && entry.contentSnippet != '') {
					var content = entry.contentSnippet;
				} else {
					var content = entry.content;
				}
							
			}
			
		}
		
		html += '</ul>' +
			'</div>'
			
		html += '</div>';
		
		$(e).html(html);*/

	};
	
	function formatFilesize(bytes) {
		var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
		var e = Math.floor(Math.log(bytes)/Math.log(1024));
		return (bytes/Math.pow(1024, Math.floor(e))).toFixed(2)+" "+s[e];
	}

	function getXMLDocument(string) {
		var browser = navigator.appName;
		var xml;
		if (browser == 'Microsoft Internet Explorer') {
			xml = new ActiveXObject('Microsoft.XMLDOM');
			xml.async = 'false'
			xml.loadXML(string);
		} else {
			xml = (new DOMParser()).parseFromString(string, 'text/xml');
		}
		return xml;
	}

})(jQuery);

