// JavaScript Document

function saveAlbum() {
    return;
}

function saveSongs(pk)
{
	deleteCookie('basket', '/');
	price=0;
	sng=new Array();
	sng_pk='';
	if(typeof(pk)!='undefined')
	{
		sng[pk]=new Object(parse_str(songs[pk]));
		price=parseFloat(sng[pk]['price']);
	}
	else
	{
		lst=document.getElementById('traklist').getElementsByTagName('input');
		for(i=0; i<lst.length; i++) if (lst[i].type=='checkbox' && lst[i].checked)
		{
			pk=lst[i].id.substr(8);
			sng[pk]=new Object(parse_str(songs[pk]));
			price+=parseFloat(sng[pk]['price']);
			sng_pk += pk + ',';
		}
	}
	if(sng.length>0)
		{
		//var obj=new Object({'artist':parse_str(artist), 'album':parse_str(album), 'songs':sng_pk});
		setCookie('basket', sng_pk, null, '/');
		}
	else
		deleteCookie('basket', '/');
    
	price=Math.round(price*100)/100;

	return price;

}

function buyAlbum(obj, id, price, mult)
{
	if (isDisabledButtons()) {
		return false;
	}
	
	if (buy_mmplayer != 'undefined') {
		//document.location = '/publish/mmplayer-buy/';
		return Buy.confirm(id,obj,'','');
	}

	if (is_special_user) {
	   var msg = 'Album is available for downloading';
	}else{
		if ( mult != undefined && mult > 0 && mult < 1 )
			var msg = 'This item costs <b>$'+price+'</b>. You have '+Math.floor(mult*100)+'% Wondertime discount and your account will be charged $'+(Math.ceil(price*(1-mult)*100)/100);
		else if( balance >= price )
			var msg = 'Your account will be charged at the rate of <b>$' + price + '</b> for this operation.';
	}
    
/*
	if (msg && !confirm(msg)) {
		return false;
	}
*/
	
	head = "Download album &laquo;"+$(obj).attr('rel')+"&raquo;";
	return Buy.confirm(id,obj,msg,head);
	
	return false;    
}

function buyAlbum_confirm(id){
	
	disableAllButtons();
	changeToWaitingButton(id, 'album');
	JsHttpRequest.query(
		'/basket/buyAjax/', // backend
		{
			'buy_type': 'A',
			'buy_id': id
		},
		function(result, errors) {
			changeToDownloadButton(id, 'album', result['type']);
			enableAllButtons();
			showDownloadMessage(result, 'album');
			
		},
		true // disable caching
	);

}

var Buy = {
	  film_window_close : function(){
			$('#film-window').hide();
			toneBody(false);
			return false;
	  },
	  confirm : function(id,h, mess, head, t){
			type = t || false;
			head = head || '';
			$('#film-window-content').html(mess);
			$('#film-window-content-h').html(head);
			//if(typeof(h)!=='object') $('#film-window-ok').attr('href',h);
			//else{
				//if($(h).attr('href')) $('#film-window-ok').attr('href',$(h).attr('href'));
				//else
				$('#film-window-ok').one('click', function(){ $('#film-window').hide();
										 if(!type && !id) { checkout_confirm(); return false; }
										 if(!type)
											 buyAlbum_confirm(id);
										 else 
											buySong_confirm(id);
										 return false; });
				
			//}
			//toneBody(true);
			
			if( $.browser.msie )
				$('#film-window').css('margin-top', ($('#film-window').scrollTop()+$(window).scrollTop()-200)+'px');
			
			if (typeof buy_mmplayer != 'undefined') {
				document.location = '/publish/mmplayer-buy/';
				return false;
			}
			
			$('#film-window').show();
			return false;
	  }
}

function buyAlbum_old(id, price, mult)
{
	
	if (isDisabledButtons()) {
		return false;
	}

    if (is_special_user) {
        var msg = 'Album is available for downloading';
    }else{
		if ( mult != undefined && mult > 0 && mult < 1 )
			var msg = 'This item costs $'+price+'. You have '+Math.floor(mult*100)+'% Wondertime discount and your account will be charged $'+(Math.ceil(price*(1-mult)*100)/100);
		else
			var msg = 'Your account will be charged at the rate of $' + price + ' for this operation.';
    }
    

	if (!confirm(msg)) {
		return false;
	}

	if (isDisabledButtons()) {
		return false;
	}

	
	disableAllButtons();
	changeToWaitingButton(id, 'album');
	JsHttpRequest.query(
		'/basket/buyAjax/', // backend
		{
			'buy_type': 'A',
			'buy_id': id
		},
		function(result, errors) {
			changeToDownloadButton(id, 'album');
			enableAllButtons();
			showDownloadMessage(result, 'album');
			
		},
		true // disable caching
	);
	
	//alert("Ok");
	return false;
}

function buySong(obj, id, price, mult)
{
    if (isDisabledButtons()) {
    	return false;
    }
    
    if (typeof buy_mmplayer != 'undefined') {
		document.location = '/publish/mmplayer-buy/';
		return false;
	}
    
    if (is_special_user) {
        var msg = 'Track is available for downloading';
    }else{
		if ( mult != undefined && mult > 0 && mult < 1 )
			var msg = 'This item costs $'+price+'. You have '+Math.floor(mult*100)+'% Wondertime discount and your account will be charged $'+(Math.ceil(price*(1-mult)*100)/100);
		else if( balance >= price )
			var msg = 'Your account will be charged at the rate of $' + price + ' for this operation.';
    }  
/*
    if (msg && !confirm(msg)) {
    	return false;
    }  
*/

	head = "Download song &laquo;"+$(obj).attr('rel')+"&raquo;";
	return Buy.confirm(id,obj,msg,head,1);
}

function buySong_confirm(id){
	
	disableAllButtons();
	
	if (typeof buy_mmplayer != 'undefined') {
		document.location = '/publish/mmplayer-buy/';
		return false;
	}
	
	changeToWaitingButton(id, 'song');
	JsHttpRequest.query(
		'/basket/buyAjax/', // backend
		{
			'buy_type': 'S',
			'buy_id': id
		},
		function(result, errors) {
			changeToDownloadButton(id, 'song', result['type']);
			enableAllButtons();
			showDownloadMessage(result, 'song');
			
		},
		true // disable caching
	);
	
}

function buySong_old(id, price, mult)
{
    $('#pk_song_'+id).attr('checked', true);
    
    return;
    
    if (isDisabledButtons()) {
    	return false;
    }
    
    if (is_special_user) {
        var msg = 'Track is available for downloading';
    }else{
		if ( mult != undefined && mult > 0 && mult < 1 )
			var msg = 'This item costs $'+price+'. You have '+Math.floor(mult*100)+'% Wondertime discount and your account will be charged $'+(Math.ceil(price*(1-mult)*100)/100);
		else
			var msg = 'Your account will be charged at the rate of $' + price + ' for this operation.';
    }  

    if (!confirm(msg)) {
    	return false;
    }

    if (isDisabledButtons()) {
    	return false;
    }

	disableAllButtons();
	changeToWaitingButton(id, 'song');
	JsHttpRequest.query(
		'/basket/buyAjax/', // backend
		{
			'buy_type': 'S',
			'buy_id': id
		},
		function(result, errors) {
			changeToDownloadButton(id, 'song');
			enableAllButtons();
			showDownloadMessage(result, 'song');
			
		},
		true // disable caching
	);
	
	//alert("Ok");
	return false;
}

function checkout(ptr)
{
	if (isDisabledButtons()) {
		return false;
	}
	
	if (typeof buy_mmplayer != 'undefined') {
		document.location = '/publish/mmplayer-buy/';
		return false;
	}
	
	p = saveSongs();

	if (p!=0)
	{        
	    deleteCookie('basket', '/');
        
	    if (p > balance) {
		openPopupNotEnouthWindow();
		return false;
	    }
        
	    msg = 'Your account will be charged at the rate of $' + p + ' for this operation.';

	    if (isDisabledButtons()) {
	    	return false;
	    }

		head = "Download songs";
		return Buy.confirm(false,ptr,msg,head,false);

	} else {
		alert('Please, choose tracks for downloading.');
		return false;
	}
	
	return false;
}
function checkout_confirm(){
		disableAllButtons();
	    changeToWaitingButton(0, 'songs');
	    var ids = new Array();
	    var lst = document.getElementById('traklist').getElementsByTagName('input');
	    for(i=0; i<lst.length; i++) { 
	    	if (lst[i].type=='checkbox' && lst[i].checked) {
	    		ids[ids.length] = lst[i].id.substr(8);
	    	}
	    }
	    JsHttpRequest.query(
	    	'/basket/buyAjax/', // backend
	    	{
	    		'buy_type': 'S',
	    		'buy_id': ids
	    	},
	    	function(result, errors) {
	    		changeToDownloadButton(0, 'songs');
	    		enableAllButtons();
	    		showDownloadMessage(result, 'songs');
	    	},
	    	true // disable caching
	    );
}
function showDownloadMessage(result, type)
{
	if ("error" == result["type"]) {
		switch (result["data"]) {
			case "noauth":
				alert("Error!!!\nYou are not authtorized. Please login.");
				break;
			case "notfound":
				alert("Error!!!\nItem not found.");
				break;
			case "notenougthmoney":
				openPopupNotEnouthWindow();
				//alert("Error!!!\nYou do not have enought money.");
				break;
			case "busy":
				alert("Error!!!\nWe are sorry but the server is closed for maintainance.");
				break;
			case "24limit":
				alert("Error!!!\nSorry, due to technical reasons and in order to provide better service and high speed downloads we limit daily download by "+result["limit"]+" tracks per day. Sorry for inconvenience.");
				break;
		}
	} else {
		correctlyPurchased(result, type);
		if (typeof(updateWondertimeCounter) == 'function') updateWondertimeCounter();
	}
}

function changeToWaitingButton(id, type)
{
	var obj = document.getElementById('downbut_' + type + "_" + id);
	var obj_unc = document.getElementById('downbut_' + type + "_" + id + "_unc");
	if (!obj || !obj_unc) {
		return false;
	}

	obj.style.display = "none";
	obj = document.getElementById('downbut_' + type + "_" + id + "_don");
	if (obj) {
		obj.style.display = "none";
	}

	obj_unc.style.display = "";
}

function correctlyPurchased(data, type)
{
	var obj = document.getElementById('auth_user_balance');
	if (obj && data["balance"]) {
		obj.innerHTML = "" + correctPrice(data["balance"]);
	}

	openPopupWindow();
}

function correctPrice(price)
{
	price = Math.ceil(price*100); // bug 0.00000001
	price = price + "";
	while (price.length < 3) {
		price = "0" + price;
	}

	var start_price = price.substr(0, price.length - 2);
	var end_price = price.substr(price.length - 2, 2);
	return start_price + "." + end_price;
}

function changeToDownloadButton(id, type, msg)
{
	var obj = document.getElementById('downbut_' + type + "_" + id + "_don");
	var obj_dwnl = document.getElementById('downbut_' + type + "_" + id);
	var obj_unc = document.getElementById('downbut_' + type + "_" + id + "_unc");
	if (!obj || !obj_unc) {
		return false;
	}

	if( msg == 'error' )
	{
	    obj_dwnl.style.display = "block";
	    obj_unc.style.display = "none";
	    obj.style.display = "none";	    
	}
	else
	{
	    obj_unc.style.display = "none";
	    obj.style.display = "";	    
	}
}

function disableAllButtons()
{
	disabled_buttons = true;
}

function enableAllButtons()
{
	disabled_buttons = false;
}

function isDisabledButtons()
{
	return disabled_buttons;
}

	
function fnSelectionInverse(p)
{	
	chboxes = document.getElementById('traklist').getElementsByTagName('input');
	for (i=0; i<chboxes.length; i++) {
		chboxes[i].checked=(p.checked)?(true):(false);
	}
}

function closePopupWindow()
{
	var obj = document.getElementById('popup');
	if (obj) {
		obj.style.display = "none";
	}
}

function openPopupWindow()
{
	var obj = document.getElementById('popup');
	if (obj) {
		var scrollTop = 0;
		if (window.pageYOffset) {  
			scrollTop = window.pageYOffset 
		} else if(document.documentElement && document.documentElement.scrollTop) { 
			scrollTop = document.documentElement.scrollTop; 
		} else if(document.body) { 
			scrollTop = document.body.scrollTop; 
		}

		var eTop;
		if (document.body.clientWidth <= 550) {
			obj.style.top = scrollTop + 30 + "px";
		} else {
			obj.style.top = scrollTop + 150 + "px";
		}

		obj.style.display='block';
	}
}

function openPopupNotEnouthWindow()
{
	var obj = document.getElementById('popup_not_enouth_money');
	if (obj) {
		var scrollTop = 0;
		if (window.pageYOffset) {  
			scrollTop = window.pageYOffset 
		} else if(document.documentElement && document.documentElement.scrollTop) { 
			scrollTop = document.documentElement.scrollTop; 
		} else if(document.body) { 
			scrollTop = document.body.scrollTop; 
		}

		var eTop;
		if (document.body.clientWidth <= 550) {
			obj.style.top = scrollTop + 30 + "px";
		} else {
			obj.style.top = scrollTop + 150 + "px";
		}

		obj.style.display='block';
	}
}

function closePopupNotEnouthWindow()
{
	var obj = document.getElementById('popup_not_enouth_money');
	if (obj) {
		obj.style.display = "none";
	}
}

function enableDownloadSelectedButton()
{
    var btn = document.getElementById('downbut_songs_0_don');
    if (btn) {
    	if( btn.style.display == 'none' )
		return;
	}
	
	if (typeof buy_mmplayer != 'undefined') {
		$('#downbut_songs_0').bind('click',function(){
			document.location = '/publish/mmplayer-buy/';
			return false;
		});
	}

    document.getElementById('downbut_songs_0').style.display = 'block';
    document.getElementById('downbut_songs_0_don').style.display = 'none';
}

