/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
 */
jQuery.extend({
/**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getUrlParam("paramName");
*/
 getUrlParam: function(strParamName){
	  var strReturn = "";
	  var strHref = window.location.href;
	  var bFound=false;

	  var cmpstring = strParamName + "=";
	  var cmplen = cmpstring.length;

	  if ( strHref.indexOf("?") > -1 ){
	    var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	    var aQueryString = strQueryString.split("&");
	    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
	      if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
	        var aParam = aQueryString[iParam].split("=");
	        strReturn = aParam[1];
	        bFound=true;
	        break;
	      }

	    }
	  }
	  if (bFound==false) return null;
	  return strReturn;
	}
});

/**
 * Create update box of following structure.
 * <div class="tab">
 * 	<div class="wrap1">
 * 		<div class="sidebar">
 * 			<div class="roundbox">
 * 				<div class="i1">
 * 					<ul class="def-list">
 * 						<li><strong>Patient:</strong> <span>###PATIENT###</span></li>
 * 						<li><strong>Diagnosis:</strong> <span>###DIAGNOSIS###</span></li>
 * 						<li><strong>Pictures:</strong> <span>###PICTURES###</span></li>
 * 						<li><strong>Therapy Time:</strong> <span>###THERAPY TIME###</span></li>
 * 					</ul>
 * 					###DESCRIPTION###
 * 				</div>
 * 			</div>
 * 			<img src="###SIDE###" />
 * 		</div>
 * 		<div class="maincol">
 * 			<div class="trailer" width="640" height="360" file="###FLV###" image="###PICTURE.BIG"></div>
 * 			<div class="thumbs">
 * 				<img src="###01###" />
 * 				<img src="###02###" />
 * 				<img src="###03###" />
 * 				<img src="###04###" />
 * 			</div>
 * 			<div class="roundbox">
 * 				<div class="i1">
 * 					<h2>Members Comments</h2>
 * 					<div class="scrollable">
 * 						<dl class="news">
 * 							<dt>###DATE###. ###NAME###</dt>
 * 							<dd>###TEXT###</dd>
 * 						</dl>
 * 					</div>
 * 				</div>
 * 			</div>
 * 		</div>
 * 	</div>
 * 	<div class="wrap3">
 * 		<img src="images/view.gif" alt="View this episode" />
 * 		<div class="rate">
 * 			<strong>Rate this episode:</strong>
 * 			<span class="rating">
 * 				<img src="images/no-star.gif" />
 * 				<img src="images/no-star.gif" />
 * 				<img src="images/no-star.gif" />
 * 				<img src="images/no-star.gif" />
 * 				<img src="images/no-star.gif" />
 * 			</ul>
 * 			Lorem ipsum sit
 * 		</div>
 * 	</div>
 * </div>
 */
function createBox(data)
{
	with (data)
	{
		var c = '<dl class="news">'; //Generate comments
		for (i in comments)
		{
			c = c + '<dt>' + comments[i].name + '</dt>';
			c = c + '<dd>' + comments[i].text + '</dd>';
		}
		c = c + '</dl>';
		var trailer_code = '<div class="trailer" width="640" height="360" file="' + flv + '" image="' + pictures.big + '" streamer="' + flv + '"></div>';
		if ($.cookie('voted_'+set_id)) //Voted
			var html = '<div class="tab"><div class="wrap1"><div class="sidebar"><div class="roundbox"><div class="i1">' +
			'<ul class="def-list"><li><strong>Patient:</strong> <span>' + patient + '</span></li><li><strong>Diagnosis:' +
			'</strong> <span>' + diagnosis + '</span></li><li><strong>Pictures:</strong> <span>' + pictures_amount +
			'</span></li><li><strong>Therapy Time:</strong> <span>' + therapy_time +
			'</span></li></ul>' + description + '</div></div><img src="' + pictures.side +
			'" /></div><div class="maincol">' + trailer_code + '<div class="thumbs"><img src="' + pictures['01'] + '" /><img src="' + pictures['02'] +
			'" /><img src="' + pictures['03'] + '" /><img src="' + pictures['04'] + '" /></div><div class="roundbox">' +
			'<div class="i1"><h2>Members Comments</h2><div class="scrollable">' + c + '</div></div></div></div></div>' +
			'<div class="wrap3"><a href="' + join + '"><img src="images/view.gif" alt="View this episode" /></a>' +
			'<div class="rate"><strong id="t_' + set_id + '">&nbsp;Episode\'s&nbsp;rating:&nbsp;</strong><span class="rated" id="s_' + set_id + '">' +
			createRating(amount, votes) + '</span><span class="votes" id="v_' + set_id + '">' + createVotes(amount, votes) + '</span></div></div></div>';
		else //Not voted
			var html = '<div class="tab"><div class="wrap1"><div class="sidebar"><div class="roundbox"><div class="i1">' +
			'<ul class="def-list"><li><strong>Patient:</strong> <span>' + patient + '</span></li><li><strong>Diagnosis:' +
			'</strong> <span>' + diagnosis + '</span></li><li><strong>Pictures:</strong> <span>' + pictures_amount +
			'</span></li><li><strong>Therapy Time:</strong> <span>' + therapy_time +
			'</span></li></ul>' + description + '</div></div><img src="' + pictures.side +
			'" /></div><div class="maincol">' + trailer_code + '<div class="thumbs"><img src="' + pictures['01'] + '" /><img src="' + pictures['02'] +
			'" /><img src="' + pictures['03'] + '" /><img src="' + pictures['04'] + '" /></div><div class="roundbox">' +
			'<div class="i1"><h2>Members Comments</h2><div class="scrollable">' + c + '</div></div></div></div></div>' +
			'<div class="wrap3"><a href="' + join + '"><img src="images/view.gif" alt="View this episode" /></a>' +
			'<div class="rate"><strong id="t_' + set_id + '">Rate this episode:</strong><span class="rating" id="s_' +
			set_id + '">' + createRating(amount, votes) + '</span><span class="votes" id="v_' + set_id + '">' + createVotes(amount, votes) + '</span></div></div></div>';
	}
	return html;
}
function createVotes(amount, votes)
{
	return Math.round(amount/votes*100)/100 + ' (' + votes + ' votes)';
}
function createRating(amount, votes)
{
	var html = '';
	var rating = Math.round(amount*2/votes)/2; //We round to half
	for (var i = 1; i <= Math.floor(rating); i++)
		html = html + '<img src="images/star.gif" />';
	if (Math.ceil(rating) != Math.floor(rating))
		html = html + '<img src="images/half-star.gif" />';
	for (var i = Math.ceil(rating) + 1; i <= 5; i++)
		html = html + '<img src="images/no-star.gif" />';
	return html;
}
function createBoxTop()
{
	var html = '<div class="box-top"></div>';
	return html;
}

function resort(event)
{
	$('#setscontainer').html('');
	var sort_by = $(this).attr('href').replace('#', '');
	_BOFFIN_SET_DATA = (sort_by == 'newest') ? _BOFFIN_SET_DATA.sort(cmp_newest) : _BOFFIN_SET_DATA.sort(cmp_best);
	if (sort_by == 'newest')
	{
		$('.tabset .newpatients').parent('li').addClass('active');
		$('.tabset .diagnoses').parent('li').removeClass('active');
	}
	else
	{
		$('.tabset .newpatients').parent('li').removeClass('active');
		$('.tabset .diagnoses').parent('li').addClass('active');
	}
	switch (window.location.pathname)
	{
		case '/':
		case '/index.php':
			var start = 0;
			var end = Math.round(_BOFFIN_SET_DATA.length / 2) - 1;
			break;
		case '/tour.php':
		default:
			var start = Math.round(_BOFFIN_SET_DATA.length / 2);
			var end = _BOFFIN_SET_DATA.length - 1;
			break;
	}
	for (var i=start; i<=end; i++)
	{
		if (i != start)
			$('#setscontainer').append(createBoxTop());
		if (i == end)
			$('#setscontainer').append(createBox(_BOFFIN_SET_DATA[i]).replace('wrap3', 'wrap2'));
		else
			$('#setscontainer').append(createBox(_BOFFIN_SET_DATA[i]));
	}
	$("a[href*='tour.php']").each(function() {var x = $(this).attr('href').replace(/#.*$/, '');
		$(this).attr('href', x + '#' + sort_by);});
	/* Make voting */
	$('.rating img').bind('mouseenter', function() {$(this).prevAll('img').andSelf().attr('src', 'images/star.gif'); $(this).nextAll('img').attr('src', 'images/no-star.gif');});
	$('.rating img').bind('mouseleave', function() {$(this).prevAll('img').andSelf().attr('src', 'images/no-star.gif');});
	$('.rating img').bind('click', do_vote);
	enflash(".trailer");
}
function cmp_newest(a, b) {return b.date - a.date;}
function cmp_best(a, b) {return (b.amount/b.votes) - (a.amount/a.votes);}

$(document).ready(function(){

	var nats = $.getUrlParam('nats');
	join = 'http://join.mydrfeelgood.com/signup/signup.php?nats=' +  ((nats) ? nats : 'MC4wLjEuMS4wLjAuMC4w') + '&step=2';
	/* Make tab changing */
	$('.tabset a').bind('click', resort);
	switch (window.location.hash)
	{
		case '#best':
			$('.tabset .diagnoses').trigger('click');
			break;
		case '#newest':
		default:
			$('.tabset .newpatients').trigger('click');
			break;
	}
	$('a.bookmark').bind('click', bookmark);
	/* Insert trailers */
});

function enflash(elements)
{
	var htmlOptions = {
		src: 'player.swf',
		width: '',
		height: '',
		flashvars: {controlbar: 'over', 'file': '', 'image': '', 'streamer': ''}
	};
	var pluginOptions = {version: 8};

	$(elements).each(function(){
		var elementOptions = {
			src: $(this).attr('src'),
			width: $(this).attr('width'),
			height: $(this).attr('height'),
			flashvars: {}
		};
		for (i in htmlOptions.flashvars)
			elementOptions.flashvars[i] = $(this).attr(i);
		var actualOptions = $.extend(true, htmlOptions, elementOptions);
		if ($(this).attr('file'))
		{
			$(this).flash(actualOptions, pluginOptions);
		}
		else
		{
			$(this).html('<img src="' + actualOptions.flashvars['image'] + '" width="' + actualOptions.width + '" height="' + actualOptions.height + 
				'" />');
		}
	});
}

function bookmark()
{
	url = location.href;
	title = document.title;
	
	if (window.sidebar) //Mozilla Firefox
	{
		window.sidebar.addPanel(title, url, "");
	}
	else if (window.sidebar) //IE Favorite
	{
		window.external.AddFavorite(url, title);
	}
	else if (window.opera && window.print) //Opera
	{
		var a = document.createElement('A');
		if (!a) return false; //IF Opera 6
		a.setAttribute('rel', 'sidebar');
		a.setAttribute('href', url);
		a.setAttribute('title', title);
		a.click();
	}
	else
	{
		alert("Your browser doesn't support automatic bookmarking. Press Ctrl-D to bookmark the page manually!");
	}
	return false;
}

function do_vote()
{
	var set_id = $(this).parent().attr('id').replace('s_', '');
	var rating = $(this).prevAll('img').length + 1;
	$('#v_'+set_id).html('<img src="images/icon-loading.gif" />');
	$.post('http://mydrfeelgood.com/vote.php', {'set_id':set_id, 'rating':rating}, cb_vote, 'json');
}

function cb_vote(data, status)
{
	$('#s_'+data.set_id).html(createRating(data.amount, data.votes));
	$('#s_'+data.set_id+' img').css('cursor', 'default');
	$('#v_'+data.set_id).html(createVotes(data.amount, data.votes));
	$('#t_'+data.set_id).html("&nbsp;Episode's&nbsp;rating:&nbsp;");
	$.cookie('voted_'+data.set_id, '1', {path:'/', domain:'mydrfeelgood.com', expires:90});
}

