var useGoogle = false, MAX_POSTS = 6,
	FEED_RSS2 = 'http://fluxinc.ca/blog/?feed=rss2&tag=%s&number=%d',
	LOCAL_FEED_RSS2 = '/blog/?feed=rss2&tag=%s&number=%d',
	POST_RSS2 = 'http://fluxinc.ca/blog/?feed=rss2&p=%d',
	posts, newdelay = 0, divcolor, division = '', g_tags='',fheight, g_stag,
	params = window.location.href.match(/fluxinc.ca\/([a-z]+)\/([^\/]+)/);

if (params !== null) {
  post = params[2];
  division = params[1];
}

function loadFeed(stag, spost) {
	g_stag = stag;
	tag = stag ? stag : g_tags;
	var BASE_URL = useGoogle ? FEED_RSS2 : LOCAL_FEED_RSS2,
		URL = $.sprintf( BASE_URL, tag, MAX_POSTS ); 
	if ( useGoogle ) {
		var feed = new google.feeds.Feed( URL );
		feed.load(function (result) {
			parseFeed(result);
		});
	} else {
		$.ajax({
	        type: "GET",
			url: URL, 
			dataType: "xml",
			success: function (xml) {
				parseFeed(xml);
			}
		});
	}
}

function loadPost(tag) {
	var BASE_URL = useGoogle ? FEED_RSS2 : LOCAL_FEED_RSS2,
		URL = $.sprintf( BASE_URL, tag, MAX_POSTS ); 
	if ( useGoogle ) {
		var feed = new google.feeds.Feed( URL );
		feed.load(function(result) {
			if (!result.error) {
				if ( result.feed.entries.length > 0 ) {
					showPost(result.feed.entries[0]);
				}
			}
		});
	} else {
		$.ajax({
	        type: "GET",
			url: URL,
			dataType: "xml",
			success: function(result) {
				entries = $(result).find('item');
				if ( entries.length > 0 ) {
					showPost(entries[0]);
				}
			}
		});
	
	}
}

function parseFeed(result) {
	if ( useGoogle && !result.error) {
		feed = result.feed;
	} else if ( ! useGoogle ) {
		feed = {};
		feed.entries = $(result).find('item');
	} else {
		feed = false;
	}
	
	if (feed) {
		$( '#btnlist' ).empty();	 
		posts = feed.entries;
		var	li, rp = ( post !== "" ) ? post : false;
		if ( !rp && feed.entries.length > 0 ) {
			showPost(feed.entries[0]);
		} else if (rp) {
			loadPost(post);
    	if (post==327) {
    	 setTimeout('showTheatre();',1000);
    	}
		}
		var i = 0;
		$(feed.entries).each(function(i, post){
			if ( i < MAX_POSTS ) {
				parsePost(rp, i, post);
				i++;
			}
		});
		if (g_stag) {
			showPreviews();
		}
	}	
}
function parsePost(rp, i, post) {
	if ( ! useGoogle ) {
		newpost = new Object();
		newpost.title = $(post).find('title').text();
		newpost.content = $(post).find('[nodeName="content:encoded"]').text();
		newpost.link = $(post).find('link').text();
		post = newpost;
	    var src = post.content.match(/src=.*\>/);
	} else {
	    var src = post.content.match(/src=\".*\"\>/);
	}
	var p = post.link.match(/[0-9]+/),
		 clickCmd = $.sprintf('showPost(posts[%d]);', i);
	
	if ( rp && p == rp ) {
		showPost(post);
	}
	
	$( '#btnlist' ).append( 
		$($.sprintf('<li id="p%d" onclick="%s"/>', p, clickCmd) )
		.hover(function () {
			if (typeof this.showing == "undefined" || ! this.showing ) {
				this.showing = true;
				$('.tdiv', this).show( "slide", {direction: "up"}, 250);
			}
		}, function () {
			this.showing = false;
			$('.tdiv', this).hide( "slide", {direction: "up"}, 500);
		})
		.append( $('<div class="tdiv">').text(post.title).hide()).hide()
	);
	if ( src ) {
		var img = $('<img '+ src );
		img.attr('width', '366')
			.attr('height', '80');
		$( '#p'+p ).append( img ).hide();
	}
}
function cropImage(img, width, height, x, y) {
	var newdiv = $('<div class="imgdiv">')
		.css('background-image','url('+$(img).attr('src')+')')
		.css('background-position', x+'px ' + y + 'px')
		.css('background-repeat', 'no-repeat')
		.css('width',width+'px')
		.css('height',height+'px');			
	$(img).before(newdiv).remove();		
}

function formResponse(responseText, statusText) {
  if (responseText) {
    $('#formBadData').hide();
    $('div#formInput').fadeOut('fast');
    setTimeout("$('div#formSuccess').fadeIn('fast');", 500); 
  } else {
    $('#formBadData').show();
  }
}
function showPost(post) {
	$( '#postTitle, #postText' ).hide();

	if ( post ) {
		if ( ! useGoogle ) {
			newpost = new Object();
			newpost.title = $(post).find('title').text();
			newpost.content = $(post).find('[nodeName="content:encoded"]').text();
			newpost.link = $(post).find('link').text();
			post = newpost;
		}

		$( '#postTitle' ).text( post.title );
		if ( post.content ) {
			$( '#postText' ).html( post.content );
		}
	}	
	$( 'img', '#postText' ).each(function() {
		cropImage( this, 500, 150, -187, 0 );
	});
	$( '#postTitle, #postText' ).fadeIn(250);
  var options = { 
    success: formResponse, 
    dataType:  'json'
  };   
	$('form.ajaxForm').ajaxForm(options);
}

function loadFlash() {
	
  swfobject.embedSWF("flash/"+division+"Intro.swf", "topflash", "920", fheight, "9.0.0", "", null, {
      wmode: "transparent", 
      flashVars: ( "loadVideo=" + ( $.cookie(division+"Intro") =="1" ? 'hide' : 'show' ) )
    });
  
}

function moveFlashDown() {
	if ( fheight == "310" ) {
		$('#bgpost')
			.css( "position", "relative" )
			.css( "z-index", "100")
			.animate( {top:"-150px"},250);
	}
	showPreviews();
}

function showPreview(id) {
	$("#"+id)
		.show()
		.animate({backgroundColor: divcolor},100)
		.animate({backgroundColor: 'white'},500);
	$('img', "#"+id).hide().fadeIn("slow");
}

function showPreviews() {
	$('div#bgbtns ul li').each(function() {
		var cmd = $.sprintf('showPreview("%s");', $(this).attr('id') );
		setTimeout( cmd, newdelay );
		newdelay = newdelay + 100;
	});
}

function playFlv() {
	var w = 509, h = 369, url = 'http://fluxinc.ca/videos/cardbuilder.flv';
	$.prompt($.sprintf(FLV_PLAYER, w, h, url, w, h, url) );
}

function gup( name ) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ) {
		return "";
	} else {
		return results[1];
	}
}

function showTheatre() {
  var players = [
    [420,235,"hdtv_web.f4v"],
    [420,230,"xphonefinal_web.f4v"],
    [420,324,"cardbuilder_web.f4v"],
    [420,254,"wolves_web.f4v"],
    [420,237,"twotone_web.f4v"],
    [420,237,"ireland_web.f4v"]
    ],s=[],params="type=rtmp&amp;streamer=rtmp://tj3xpm8zp1y.rtmphost.com/streams&amp;file=";
    
  	for (var i=0;i<players.length;i++) {
  			s[i] = new SWFObject('/videos/player.swf','player',players[i][0],players[i][1],'9');
  			s[i].addParam('flashvars',params+players[i][2]);
  			s[i].write('player'+i);
  			$('#player'+i).css('margin-top','20px');    	
  	}
  	$('.theatrecarousel').carousel({ loop: true });
  	setTimeout('$(".theatreul").animate({left:0,right:0},250);',250);
}

$(function() {
  $.cookie(division+"Intro", '1');
	$('#home').click(function() {
		window.location='?div=';
	});
	$('#about').click(function() {
		loadPost('aboutus');
	});
	$('#products').click(function() {
		loadFeed(division+'products');
	});
	$('#contactus').click(function() {
		loadPost('contactus');
	});
	division = ( params !== null ) ? params[1] : gup('div');
	divcolor = (division == 'medical' ) ? 'blue' : (division == 'media') ? 'green' : 'orange';
	g_tags = (division == 'medical' ) ? 'medicalnews' : (division == 'media') ? 'medianews' : (division == 'enterprise') ? 'enterprisenews' : 'news';
	fheight = ( division == 'enterprise' || division == 'medical' ) ? "160" : "310";
	
	loadFeed(false, post);
	loadFlash();
	var config = new hbl.hwindow.config();
	config.vars["start_hidden"] = 1;
	wc_init("1498-29812142-10-6247", config);
});