var ultimatePayParams;

function buy(amount, bucks_type, app_id) 
{
    bucks_type = typeof(bucks_type) != 'undefined' ? bucks_type : 'breakout-bucks';
    app_id = app_id || 1;

	if (appMode == 'facebook')
	{
		promptFbBuy(amount, bucks_type, app_id);
	} else {
        if(appMode != 'satellite'){
            app_mode_param = 'default';
        }else{
            app_mode_param = appMode;
        }
		$.post('/commerce/currency/args', {bucks:amount, bucks_type: bucks_type, app_mode: app_mode_param, app_id: app_id}, function(response)
		{
			ultimatePayParams = jQuery.parseJSON(response);
			
			ulp.ultimatePay = true;
			ulp.displayUltimatePay();
				
			ulp.on('paymentSuccess', paymentSuccess_Handler);
		});
	}
}

function promptFbBuy(amount, bucks_type, facebook_app_id)
{
	var amount = amount || 0;
    bucks_type = bucks_type || 'breakout-bucks';
    facebook_app_id = facebook_app_id || 1;
	
	$.getJSON('/facebook/canvas/fb-app-info/facebook_app_id/'+facebook_app_id, function(fb)
	{
		FB.init({appId: fb.appid, status: true, cookie: true, oauth: true});
		
		var order_info = {};
		order_info.appid = fb.appid;
		order_info.amount = amount;
		order_info.bucks_type = bucks_type;
		order_info.userid = fb.userid;

		// calling the API ...
		var obj = {
		  method: 'pay',
		  order_info: order_info,
		  purchase_type: 'item',
		  test_mode: Boolean(fb.testmode)
		};
		
		FB.ui(obj, fbCreditsCallback);
	});
}

function paymentSuccess_Handler(data)
{
	$.post('/commerce/currency/credit-user/', {uuid:ultimatePayParams.userid, amount:ultimatePayParams.bucks, bucks_type: ultimatePayParams.bucks_type, change_token:data.changeToken}, function(response)
	{
        if(response == '-1'){
            return;
        }

        getUserBalance();

		if (response.indexOf('commerce') != -1)
		{
			BbPopUp.open(response);
		}
	});
}

function fbCreditsCallback(data) 
{
	if (data['order_id']) {
        getUserBalance();
		tb_remove();
	} else {
		tb_remove();
	}
};

function writeback(str) 
{
	alert(str);
}

function buyCurrency(app_id)
{
    /**
	var w = appMode == 'facebook' ? 698 : 500;
    w = appMode == 'satellite' ? 720 : w;
    **/
    var w = 500;
    app_id = app_id || 1;

	BbPopUp.open('/commerce/currency/select/no-refer/' + (new Date().getTime()) + '/app/' + appMode + '/app_id/'+ app_id + '/', {width:w, height: 474});
    if(appMode == "facebook"){
        $("#TB_window").css("top", "410px");
        $("#TB_window").css("margin-top", "0px");
    }
}

function buySongKit(sku)
{
	BbPopUp.open('/commerce/inventory/purchase/catalog/Pack/id/'+sku);
}

function buyVocalKit(sku)
{
	BbPopUp.open('/commerce/inventory/purchase/catalog/Song/vocalkit/1/id/'+sku);
}

function buyEffect(sku)
{
	BbPopUp.open('/commerce/inventory/purchase/catalog/Effect/id/'+sku);
}

function buyProfileTheme(sku)
{
	BbPopUp.open('/commerce/inventory/purchase/catalog/ProfileTheme/id/'+sku);
}

function buyStudioTheme(sku)
{
	BbPopUp.open('/commerce/inventory/purchase/catalog/StudioTheme/id/'+sku);
}

function buyAvatar(sku)
{
	BbPopUp.open('/commerce/inventory/purchase/catalog/Avatar/id/'+sku);
}

function submitToItunes(sku) {
	BbPopUp.open('/commerce/inventory/purchase/catalog/Song/itunes-submission/1/id/'+sku, {width:525, height:240});
    if(appMode == "facebook"){
        FB.Canvas.scrollTo(0,0);
        $("#TB_window").css("top", "410px");
        $("#TB_window").css("margin-top", "0px");
    }
}


function downloadSong(songId, typeHash)
{
	BbPopUp.open('/commerce/inventory/purchase/catalog/song/id/'+songId+'/typeHash/'+typeHash);

    if(appMode == "facebook"){
        FB.Canvas.scrollTo(0,0);
        $("#TB_window").css("top", "410px");
        $("#TB_window").css("margin-top", "0px");
    }
}

function getBalance(return_type)
{
	BbPopUp.open('/commerce/currency/get-balance/?return_type='+return_type);
}

function promptDownloadSuccess(name, id)
{
	BbPopUp.open('/commerce/inventory/download-success/name/'+escape(name)+'/id/'+id);
}

function getUserBalance()
{
	var balance = 0;
	
	$.post('/commerce/currency/get-balance', null, function(response)
	{
		if (response)
		{
            balance = jQuery.parseJSON(response);
            updateUserBalance(balance['accountBalance'],balance['proBucksBalance']);
		}
	});
	
	return balance;
}

function updateUserBalance(bucksBalance, proBucksBalance, addBucks, addProBucks)
{
    if(bucksBalance){
        updateBalance(bucksBalance, addBucks, "breakout-bucks");
    }
    if(proBucksBalance){
        updateBalance(proBucksBalance, addProBucks, "pro-bucks");
    }

    if (movie())
    {
        movie().updateUserBalance(bucksBalance, proBucksBalance);
    }
}

function updateBalance(amountToAdd, addIt, bucksType)
{
	var add = addIt || 'no';

	if (document.getElementById('header_currency_'+bucksType) != null)
	{
		var current = $('#header_currency_'+bucksType).text();
		var current_int = current.replace(',','');
	   
		if (add == 'yes')
		{
			var updated_balance = String(Number(current_int) + Number(amountToAdd));
		} else {
			var updated_balance = String(amountToAdd);
		}

		var nStr = '';
		nStr += String(updated_balance);
		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');
		}
		
		var formatted = x1 + x2;

		$('#header_currency_'+bucksType).text(formatted);

		return formatted;
	}
}
{
}

function updateSelector(id, type)
{
	var type = type || 'beat'

	if (movie())
	{
		movie().updateSelector(id);
	}
	else if ($('.kit-selector').length > 0 || $('.vocal-kit-selector').length > 0)
	{
		var elem;

		if (type == 'beat')
		{
			elem = $('.kit-selector .kit-' + id);
		} else {
			elem = $('.vocal-kit-selector .vocal-kit-' + id);
		}

        console.log(elem.find('.kit-buttons-wrapper:first').children('div'));
		if (elem != undefined)
		{
			elem.find('.flag:first').addClass('isOwned');
			elem.find('.kit-buttons-wrapper:first').children('div').each(function()
			{
				if ($(this).hasClass('hidden'))
				{
					$(this).removeClass('hidden');
				} else {
					$(this).addClass('hidden');
				}
			});
		}
	}
}

function updateEffectSelector(id)
{
	if (movie())
	{
		movie().updateEffectSelector(id);
	} 
	else if ($('#effect_selector'))
	{
		updateSelectorProperties($('#effect_selector'), id, "identifier", "tr");
	}
}

function updateAvatarSelector(id)
{
	if (movie())
	{
		movie().updateAvatarSelector(id);
	} 
}

function updateThemeSelector(id)
{
	if (movie())
	{
		movie().updateThemeSelector(id);
	}
	else if ($('.theme-selector').length > 0 || $('#theme_preview'))
	{
		if ($('#theme_preview'))
		{
			$('#theme_preview').slideUp().remove();
		}
		
		$('.theme-' + id).find('.flag:first').addClass('isOwned');
		$('.theme-' + id).find('.theme-buttons-wrapper:first').children('div').each(function()
		{
			if ($(this).hasClass('hidden'))
			{
				$(this).removeClass('hidden');
			} else {
				$(this).addClass('hidden');
			}
		});
	}
}

function updateSelectorProperties(element, sku, attr, children)
{
	var attr = attr || "identifier";
	var children = children || "div";
	
	element.find(children).each(function()
	{
		if ($(this).attr(attr) == sku)
		{
			$(this).find('.buy:first').parent().html("<span class=\"gray bold\">OWNED</span>");
		}
	});
}

function movie() 
{
    if (navigator.appName.indexOf("Microsoft") != -1) 
    {
    	return window["BreakoutBand"]
    }
    else 
    {
    	return document["BreakoutBand"]
    }
}


