var xmlhttp_ = {
	Create_XMLHTTP : function(inst)
	{
	//	if(this.http == null)
	//	{
			try { this.http[inst] = new XMLHttpRequest();}
			catch(e) {
				try {this.http[inst] = new ActiveXObject("Msxml2.XMLHTTP");}
				catch(e) {
					try { this.http[inst] = new ActiveXObject("Microsoft.XMLHTTP");}
					catch(e){ return false;}
				}
			}
	//	}
		
		return true;
	},
	
	ReadyState_do : function(func_call, file, inst, params)
	{
		if(this.progress[inst] == 1)
		{
			alert('In progress');
			return false;
		}
		
		this.progress = 1;
		
		this.http[inst].onreadystatechange = function()
		{
			if(xmlhttp_.http[inst].readyState == 4)
				eval(func_call);
		}
		
		var params_ = null;
		
		if(params != null)
		{
			var params_ = '';
			
			for(var i = 0 ; i < params.length ; i++)
			{
				params_ += ((i+1) % 2 == 1 ? (i == 0 ? params[i] : '&'+params[i]) : '='+escape(params[i]));
			}
		}
		
		this.http[inst].open('POST', file, true);
		this.http[inst].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.http[inst].setRequestHeader("Connection", "close");
		this.http[inst].send(params_);
	},
	
	Response_get : function(inst)
	{
		return this.http[inst].responseText;
	},
	
	End_Progress : function(inst)
	{
		this.progress[inst] = 0;
	},
	
	http : [null, null, null, null],
	progress : [null, null, null, null]
};

var starrate = {
	loadStarHandles : function(rate_score, rate_count)
	{
		this.currentRating[0] = rate_score != null ? rate_score : 0;
		this.currentRating[1] = rate_count != null ? rate_count : 0;
		
		document.getElementById('marketp_starrate').onmouseout = function() {starrate.changeRating(-1)};
		
		for(var i = 0 ; i < 5 ; i++)
			this.starHandle[i] = document.getElementById('marketp_star'+i);
		
		for(var i = 0 ; i < this.starHandle.length ; i++)
		{
			this.starHandle[i].onmouseover = function() {starrate.changeRating(this)};
			this.starHandle[i].onclick = function() {starrate.setRating(this)};
		}
		
		this.setCurrentRating();
		document.getElementById('marketp_ratingCount').innerHTML = this.currentRating[1];
	},
	
	changeRating : function(n)
	{
		if(this.stopRatingPerm == 1)
			return false;
		
		if(n == -1)
		{
			this.setCurrentRating();
			return true;
		}
		else
			var number = parseInt(n.id.replace(/[a-z_]*/i, ''));
		
		for(var i = 0 ; i < this.starHandle.length ; i++)
			this.starHandle[i].style.backgroundPosition = '0px 0px';
		
		for(var i = 0 ; i <= number ; i++)
			this.starHandle[i].style.backgroundPosition = '21px 0px';
	},
	
	setRating : function(n)
	{
		if(this.stopRatingPerm == 1)
			return false;
		
		// no more rating
		this.stopRatingPerm = 1;
		
		var number = parseInt(n.id.replace(/[a-z_]*/i, ''));
	//	alert('You rated at '+(number + 1)+' star(s)!');
		
		xmlhttp_.Create_XMLHTTP(0);
		xmlhttp_.ReadyState_do('starrate.setRating_()', 'marketplace/ajaxphp/viewalbum_ratings.ajaxphp.php?op=set&type=album&mnetid='+_GET('MnetId')+'&rating='+(number * 25), 0);
	},
	
	setRating_ : function()
	{
		var res = xmlhttp_.Response_get(0);
		if(res == '-1')
			alert('The album/track was not found under the MnetID: '+_GET('MnetId'));
		else if(res == '-2')
			alert('You have already rated this album/track.');
		else if(res == '-3')
			alert('You must be logged into your WaTunes account to rate albums.');
		else if(res != '1')
			alert('There was an error.');
		
		if(res == '-2' || res == '-3')
		{
			this.stopRatingPerm = 0;
			this.setCurrentRating();
		}
		
		if(res == '1')
			document.getElementById('marketp_ratingCount').innerHTML = parseInt(document.getElementById('marketp_ratingCount').innerHTML) + 1;
	},
	
	setCurrentRating : function()
	{
		for(var i = 0 ; i < this.starHandle.length ; i++)
			this.starHandle[i].style.backgroundPosition = '0px 0px';
		
		for(var i = 0 ; i < this.starHandle.length ; i++)
		{	
			if(this.currentRating[1] != 0 && this.currentRating[0] / this.currentRating[1] >= (i * 25) - 12.5)
				this.starHandle[i].style.backgroundPosition = '21px 0px';
		}
	},
	
	starHandle : [],
	stopRatingPerm : 0,
	currentRating : [0, 0]
};

var commentAlbum = {
	toggleComment : function(to)
	{
		if(to == 'ToComment')
		{
			document.getElementById('marketp_albumContent_3').style.display = 'none';
			document.getElementById('marketp_albumContent_0').style.display = 'none';
			document.getElementById('marketp_albumContent_1').style.display = 'none';
			document.getElementById('marketp_albumContent_2').style.display = 'none';
			document.getElementById('marketp_albumComments').style.display = 'inherit';
		}
		else if(to == 'FromComment')
		{
			document.getElementById('marketp_albumContent_3').style.display = 'inherit';
			document.getElementById('marketp_albumContent_0').style.display = 'inherit';
			document.getElementById('marketp_albumContent_1').style.display = 'inherit';
			document.getElementById('marketp_albumContent_2').style.display = 'inherit';
			document.getElementById('marketp_albumComments').style.display = 'none';
		}
	},
	
	toggleUserSubmit : function()
	{
		document.getElementById('marketp_userSubmitForm').style.display = 'inherit';
	},
	
	postComment : function()
	{
		var rating = document.getElementById('marketp_userSubRating').value;
		var anonymous = document.getElementById('marketp_userSubAnony').checked;
		var title = document.getElementById('marketp_userSubTitle').value;
		var comment = document.getElementById('marketp_userSubComment').value;
		
		xmlhttp_.ReadyState_do(
			'commentAlbum.postComment_();',
			'marketplace/ajaxphp/viewalbum_comments.ajaxphp.php?op=postComment&type=album&mnetid='+_GET('MnetId'),
			0,
			['comment', comment, 'title', title, 'rating', rating, 'anonymous', anonymous]
		);
	},
	
	postComment_ : function()
	{
		var res = xmlhttp_.Response_get(0);
		if(res == '1')
		{
			rating = document.getElementById('marketp_userSubRating');
			anonymous = document.getElementById('marketp_userSubAnony');
			title = document.getElementById('marketp_userSubTitle');
			comment = document.getElementById('marketp_userSubComment');
			rating.disabled = true;
			anonymous.disabled = true;
			title.disabled = true;
			comment.value = 'Your review has been successfully posted!!!';
			comment.disabled = true;
			document.getElementById('marketp_userSubBut').disabled = true;
		}
		else if(res == '-1')
			alert('Please enter a review.');
		else if(res == '-2')
			alert('Please enter a title.');
		else if(res == '-3')
			alert('Please chose a valid rating.');
		else if(res == '-4')
			alert('You did not state if you wanted this review to come from "Anonymous."');
	},
	
	changePage : function(page, r_amount, n_limit)
	{
		xmlhttp_.ReadyState_do('commentAlbum.changePage_();', 'marketplace/ajaxphp/viewalbum_comments.ajaxphp.php?op=changePage&mnetid='+_GET('MnetId')+'&page='+page+'&amount='+r_amount+'&nlimit='+n_limit, 0);
	},
	
	changePage_ : function()
	{
		var res = xmlhttp_.Response_get(0);
		var navigation = (res.split('<SepNode>'))[0];
		var comments = (res.split('<SepNode>'))[1];
		
		document.getElementById('marketp_commentPagination').innerHTML = navigation;
		document.getElementById('marketp_commentBody').innerHTML = comments;
	}
};

function _GET(v)
{
	var url = document.location.href;
	var file = (url.split('/'))[url.split('/').length - 1];
	var start = file.indexOf(v+'=') + v.length + 1;

	if(start == v.length)
		return null;
		
	var param = file.substring(start, file.length); param = (param.split('&'))[0]; param = (param.split('#')[0]);
	
	if(param == "")
		return null;
	
	return param;
}

// Load albums etc on home page + genre page
function loadAlbums(type, inst, id, genre)
{
	var genre_u = '';
	
	if(genre != null)
		genre_u = '&genre='+genre;
	
	xmlhttp_.Create_XMLHTTP(inst);
	xmlhttp_.ReadyState_do('loadAlbums_(\''+inst+'\', \''+id+'\')', 'marketplace/ajaxphp/home_albums.ajaxphp.php?op='+type+genre_u, inst);
}
function loadAlbums_(inst, id)
{
	res = xmlhttp_.Response_get(inst);
	document.getElementById(id).innerHTML = res;
	xmlhttp_.End_Progress(inst);
}

// Adding items to cart
function addItem(type, mnetid)
{
	xmlhttp_.Create_XMLHTTP(0);
	
	document.getElementById('marketp_i_added').style.display = 'none';
	document.getElementById('marketp_i_exists').style.display = 'none';
	document.getElementById('marketp_i_noexist').style.display = 'none';
	document.getElementById('marketp_i_failed').style.display = 'none';
	document.getElementById('marketp_i_removed').style.display = 'none';
	document.getElementById('marketp_i_rfailed').style.display = 'none';
	try{document.getElementById('marketp_CartMsgSession').style.display = 'none';} catch(e){}
	
	xmlhttp_.ReadyState_do('addItem_()', 'marketplace/ajaxphp/cart.ajaxphp.php?op=addItem&mnetid='+mnetid+'&type='+type, 0);
}
function addItem_()
{
	res = xmlhttp_.Response_get(0);
	
	if(res.replace(/ /g, '') == '1')
	{
		document.getElementById('marketp_i_added').style.display = 'inherit';
		xmlhttp_.ReadyState_do("function gc_bb(){document.getElementById('marketp_cartData').innerHTML = xmlhttp_.Response_get(0);updateCheck();xmlhttp_.End_Progress(0)}gc_bb();", 'marketplace/ajaxphp/cart.ajaxphp.php?op=getCart', 0);
	}
	else if(res.replace(/ /g, '') == '-1')
	{
		document.getElementById('marketp_i_noexist').style.display = 'inherit';
	}
	else if(res.replace(/ /g, '') == '-2')
	{
		document.getElementById('marketp_i_exists').style.display = 'inherit';
	}
	else if(res.replace(/ /g, '') == '-3')
	{
		document.getElementById('marketp_i_failed').style.display = 'inherit';
	}
	
	xmlhttp_.End_Progress(0);
}

// Remove albums from cart
function removeItem(type, mnetid)
{
	document.getElementById('marketp_i_added').style.display = 'none';
	document.getElementById('marketp_i_exists').style.display = 'none';
	document.getElementById('marketp_i_noexist').style.display = 'none';
	document.getElementById('marketp_i_failed').style.display = 'none';
	document.getElementById('marketp_i_removed').style.display = 'none';
	document.getElementById('marketp_i_rfailed').style.display = 'none';
	try{document.getElementById('marketp_CartMsgSession').style.display = 'none';} catch(e){}
	
	xmlhttp_.Create_XMLHTTP(0);
	xmlhttp_.ReadyState_do('removeItem_()', 'marketplace/ajaxphp/cart.ajaxphp.php?op=removeItem&type='+type+'&mnetid='+mnetid, 0);
}
function removeItem_()
{
	res = xmlhttp_.Response_get(0);
	
	if(res.replace(/ /g, '') == '1')
	{
		document.getElementById('marketp_i_removed').style.display = 'inherit';
		xmlhttp_.ReadyState_do("function gc_bb(){document.getElementById('marketp_cartData').innerHTML = xmlhttp_.Response_get(0);xmlhttp_.End_Progress(0);updateCheck();}gc_bb();", 'marketplace/ajaxphp/cart.ajaxphp.php?op=getCart', 0);
	}
	else if(res.replace(/ /g, '') == '0')
	{
		document.getElementById('marketp_i_rfailed').style.display = 'inherit';
	}
	
	xmlhttp_.End_Progress(0);
}

// Update sub/tax
function updateCheck()
{
	xmlhttp_.Create_XMLHTTP(4);
	xmlhttp_.ReadyState_do('updateCheck_()', 'marketplace/ajaxphp/cart.ajaxphp.php?op=Check', 4);
}
function updateCheck_()
{
	res = xmlhttp_.Response_get(4);
	subtax = res.split('|');
	sub = subtax[0].replace(/ /g, '');
	tax = subtax[1].replace(/ /g, '');
	
	document.getElementById('marketp_cartDataSub').innerHTML = sub;
	document.getElementById('marketp_cartDataTax').innerHTML = tax;
}

// Allow user to play select a song to play
function play_song(rmtp, path, title, title_, width, height)
{
	var playerContainer = document.getElementById('playerContainer');
	var playerSongTitle = document.getElementById('playerSongTitle');
	var data = 'streamer='+rmtp+'&file='+path;
	
	if(width == null)
		width = '300';
	
	if(height == null)
		height = '24';
	
	playerContainer.innerHTML =
		'<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="'+width+'" height="'+height+'">'+"\n"
		+'      <param name="movie" value="marketplace/jwplayer/player-viral.swf" />'+"\n"
		+'      <param name="allowfullscreen" value="false" />'+"\n"
		+'      <param name="allowscriptaccess" value="always" />'+"\n"
		+'      <param name="flashvars" value="'+data+'&autostart=true"'+"\n"
		+'      <embed'+"\n"
		+'        type="application/x-shockwave-flash"'+"\n"
		+'        id="player2"'+"\n"
		+'        name="player2"'+"\n"
		+'        src="marketplace/jwplayer/player-viral.swf"'+"\n" 
		+'        width="'+width+'"'+"\n"
		+'        height="'+height+'"'+"\n"
		+'        allowscriptaccess="always"'+"\n"
		+'        allowfullscreen="false"'+"\n"
		+'        flashvars="'+data+'&autostart=true"'+"\n"
		+'      />'+"\n"
		+'    </object>';
	
	playerSongTitle.innerHTML = title;
	playerSongTitle.title = title_;
}
