var msg;
TopUp.images_path = "files/design/top_up/";
TopUp.players_path = "files/design/top_up_players/";
TopUp.addPresets({    
    ".preview": {
      shaded: 1,
	  resizable: 0
    }
  });

$(document).ready(function() {
	$('.setTimeZone').each(function() {
		var currentDate= new Date();
		offset = -currentDate.getTimezoneOffset()/60;
		timezone = TimezoneDetect()/60;		
		found = false;
						
		// select the first option with a rel correspondign to the timezone
		$('.setTimeZone option').each(function() {
			if ($(this).attr('rel')==timezone && !found)
			{
				$(this).attr('selected','selected');
				$(this).attr('class','selected');
				found = true;
			}
		});
		
		if (offset!=timezone) $('#session-schedule-dst').attr('checked','checked');
		
	});
	
	//var amount = parseInt($('#amount').attr('value'))+5-parseInt($('#amount').attr('value'))%5;
	
	$("#slider").slider({
			range: "min",
			value: parseInt($('#amount').attr('value')),
			min: 0,
			max: parseInt($('#range').attr('value')),
			step: 1,
			slide: function(event, ui) {
				number = ui.value;
				if (ui.value<=0) number = 1;
				$("#amount").attr('value',number);
				
				setPricing(number);				
			}
		});
	
	$("#affiliateSlider").slider({
			range: "min",
			value: parseInt($('#affiliateCustomerDiscount').attr('value')),
			min: 0,
			max: parseInt($('#affiliatePourcentage').attr('value')),
			step: 1,
			slide: function(event, ui) {
				$('#affiliateDiscount').find('.affiliateValue').html(ui.value);
				$('#affiliateCommission').find('.affiliateValue').html(parseInt($('#affiliatePourcentage').attr('value'))-ui.value);
				$('#affiliateCustomerDiscount').attr('value',ui.value);				
			}
		});
	
	if ($("#amount").length>0) {
		var amount = parseInt($("#amount").attr('value'));
		setPricing(amount);
	}
			
	msg = $('<div></div>')
		.html('<iframe src="'+domain+'do/layoutSelection.php?mode=js" width="100%" height="100%" frameborder="0"></iframe>')
		.dialog({
			autoOpen: false,
			resizable:false,
			draggable:false,
			modal:true,
			title: 'To configure a visual, please select one in the list below',
			close:function(){
				$('body').css('overflow', 'auto');
			}
	});
	
	msg2 = $('<div></div>')
		.html('<iframe src="'+domain+'do/layoutSelection.php?mode=reload" width="100%" height="100%" frameborder="0"></iframe>')
		.dialog({
			autoOpen: false,
			resizable:false,
			modal:true,
			draggable:false,
			title: 'List of visuals',
			close:function(){
				$('body').css('overflow', 'auto');
			}
	});
	
	$('#amount').keyup(function() {
		amount = parseInt($(this).attr('value'));		
		setPricing(amount);
	});
	
	$('.selectCurrency').combox({
		width:60, 
		fontSize:'13px', 
		margin : 4,		
		onChange:function(e){
			window.location.replace(e+'&qty='+$('#amount').attr('value'));
		}
	});
	
	sliderRange();
	
	$('.sortable').sortable({
		placeholder: 'ui-state-highlight',
		stop: function(event, ui) {			
			// highlughts update
			$('.add_highlight').hide();
			$('.add_highlight:last').show();
			
			// messages update
			$('.add_message').hide();
			$('.add_message:last').show();
			
			// sponsors update
			$('.add_sponsor').hide();
			$('.add_sponsor:last').show();
			
			// moderation levels update
			$('.add_level').hide();
			$('.add_level:last').show();
			$('.twpLevel').each(function(index,elm){						
				//$(elm).children('.sessionLabel').find('span').html($(elm).children('.sessionLabel').html().substring(0,$(elm).children('.sessionLabel').find('span').html().length-3)+(index+1)+' :');			
				$(elm).children('.sessionLabel').find('span').html($(elm).children('.sessionLabel').find('span').html().substring(0,$('.twpLevel').children('.sessionLabel:first').find('span').html().length-3)+(index+1)+' :');
			});
			
		}		
	});
	
	$('#moderationOn, #moderationOff').click(function() {
		if ($('#moderationOn').is(':checked')) $('.moderationLevel').show();
		else $('.moderationLevel').hide();
	});
	
	$('.cartLine').find('td:gt(0)').click(function() {
		if ($(this).parent().find('input').is(':checked')) {
			$(this).parent().find('input').attr('checked','');
			$(this).parent().addClass('disabled');
		}
		else {
			$(this).parent().find('input').attr('checked','checked');
			$(this).parent().removeClass('disabled');
		}
		
		computeTotal();
	});
	
	$('.cartItem').click(function() {
		if ($(this).is(':checked')) {			
			$(this).parent().parent().removeClass('disabled');
		}
		else {			
			$(this).parent().parent().addClass('disabled');
		}
		
		computeTotal();
	});
	
	$('.sessionTooltip').tooltip({ 
		delay: 0, 
		showURL: false, 
		bodyHandler: function() { 			
			var tooltip = '';
			$.ajax({
				track: true,
				url: domain+'/do/sessionTooltip.php?sessionId='+$(this).parent().attr('id').substring(8,$(this).parent().attr('id').length),
				async: false,
				cache: false,				
				success: function(data) {
					tooltip = data;					
				}
			});
			return tooltip; 
		} 
	});
	
	$('.commissionTooltip').tooltip({ 
		delay: 0, 
		showURL: false, 
		bodyHandler: function() { 			
			var tooltip = '';
			$.ajax({
				track: true,
				url: domain+'/do/commissionTooltip.php?commissionId='+$(this).parent().attr('id').substring(11,$(this).parent().attr('id').length),
				async: false,
				cache: false,				
				success: function(data) {
					tooltip = data;					
				}
			});
			return tooltip; 
		} 
	});
	
	$('.twpHelp').tooltip({ 
		delay: 0, 
		showURL: false, 
		bodyHandler: function() { 			
			var tooltip = '';
			var alias = $(this).attr('id');
			$.ajax({
				track: true,
				url: domain+'/do/helpTooltip.php?alias='+alias,
				async: false,
				cache: false,				
				success: function(data) {				
					tooltip = data;					
				}
			});
			return tooltip; 
		} 
	});
	
	$('.twpColorpickers').ColorPicker({
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val(hex);
			$(el).css({backgroundColor:'#'+hex});
			$(el).ColorPickerHide();
		},
		onBeforeShow: function () {			
			$(this).ColorPickerSetColor(this.value);
		}
	}).bind('keyup', function(){
		$(this).ColorPickerSetColor(this.value);
		$(this).css({backgroundColor:'#'+this.value});
	}).each(function() {
		$(this).css({backgroundColor:'#'+this.value});
	});
	
	$('.hideDelay').animate({opacity: 0.0}, 50000, function() {            
		//$(this).css({display: 'none'});
	});
	
	$('#showReview').click(function() {
		$('#session_options').toggle();
		return false;
	});
});

function computeTotal()
{
	var total = 0;
	var currentCredits = 0;
	if($('#currentCredits').length>0) currentCredits = parseInt($('#currentCredits').html());
	
	$('.cartLine').each(function() {
		var qty = parseInt($(this).find('.cartItem').attr('value'));
		if ($(this).find('.cartItem').is(':checked')) total += qty;
	});
	
	total = total-currentCredits;
	if (total<0) total = 0;
	
	$('#suggestedTotal').html(total);
	
	if (total<=0) total = 1;
	
	$('#amount').attr('value',total);
	setPricing(total);	
}

function setPricing(amount)
{
	if ($("#slider").length>0)
	{		
		var number = amount;
		if(amount==1)number=0;
		$("#slider").slider( "value", number );
		
		$('.range').removeClass('highlight');
		var found = false;
		for(i=$('.range').length-1;i>=0;i--)
		{
			if (!found && parseInt($('.range:eq('+i+')').attr('title'))<=amount){
				$('.range:eq('+i+')').addClass('highlight');
				var price = parseFloat($('.range:eq('+i+')').find('span').attr('title'));						
				var price_highest = parseFloat($('#price_highest').html());						
				$('#price_one').html(price);
				$('#price_total').html((price*amount).toFixed(2));			
				$('#price_highest_total').html((price_highest*amount).toFixed(2));	
				
				if($('#price_highest_total').html()===$('#price_total').html()){
					$('.hiddenCredit').css('display', 'none');
				}else{
					$('.hiddenCredit').css('display', 'block');
				}
				found = true;
				
				// discount
				var discountPct = 0;
				var discountAffiliatePct = 0;
				if ($('#discountPct').length>0) discountPct = parseInt($('#discountPct').html());
				if ($('#discountAffiliatePct').length>0) discountAffiliatePct = parseInt($('#discountAffiliatePct').html());
				if (discountPct>0 || discountAffiliatePct>0)
				{					
					var discount = price*amount*(discountPct/100);
					var discountAffiliate = price*amount*(discountAffiliatePct/100);
					
					$('#discountAmount').html(discount.toFixed(2));	
					$('#discountAffiliateAmount').html(discountAffiliate.toFixed(2));	
					$('#discountTotal').html(((price*amount)-discount-discountAffiliate).toFixed(2));
				}
			}
		}
	}
}

// fonction appelée à la validation du formulaire pour vérifier que le numéro de TVA a un format correct
function validateTVA()
{
	var num;
		
	if ($('#tva').attr('value')!='')
	{
		var countries = new Array('AT','BE','BG','CY','CZ','DE','DK','EE','EL','ES','EU','FI','FR','GB','GR','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','RO','SI','SK','SE');
		var euro = false;
		var country = $('#tva').attr('value').substring(0,2);
		for(var i = 0; i<countries.length; i++) {
			if(countries[i] == country) {
				euro = true;
			}
		}
		
		if (euro)
		{
			if (num = checkVATNumber($('#tva').attr('value')))
			{
				$('#tva').attr('value',num);
				return true;
			}
			else
			{
				//tvaStatus(true,false);
				//$.scrollTo($('#topForm'),800);
				$('#tva_num_label').addClass('error');
				return false;
			}
		}
		else return true;
	}
	else return true;
}

function TimezoneDetect(){
	var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
	var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
	var intMonth;
	var intHoursUtc;
	var intHours;
	var intDaysMultiplyBy;

	//go through each month to find the lowest offset to account for DST
	for (intMonth=0;intMonth < 12;intMonth++){
		//go to the next month
		dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

		//To ignore daylight saving time look for the lowest offset.
		//Since, during DST, the clock moves forward, it'll be a bigger number.
		if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
			intOffset = (dtDate.getTimezoneOffset() * (-1));
		}
	}

	return intOffset;
}

function addParamColor(obj,min,max)
{		
	$(obj).parent().parent().find('li:last').after('<li>'+$(obj).parent().parent().find('li:last').html()+'</li>');
		
	$(obj).parent().parent().find('li:last .twpColorpickers').ColorPicker({
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val(hex);
			$(el).css({backgroundColor:'#'+hex});
			$(el).ColorPickerHide();
		},
		onBeforeShow: function () {			
			$(this).ColorPickerSetColor(this.value);
		}
	}).bind('keyup', function(){
		$(this).ColorPickerSetColor(this.value);
		$(this).css({backgroundColor:'#'+this.value});
	}).css({backgroundColor:'#FFFFFF'}).attr('value','');
	
	$(obj).parent().parent().find('.addColor').hide();
	if (max==0 || $(obj).parent().parent().find('li').length<max) $(obj).parent().parent().find('.addColor:last').show();
	
	var i = 0;
	$(obj).parent().parent().find('.removeColor').show();
	$(obj).parent().parent().find('.removeColor').each(function() {
		if (i<min) $(this).hide();
		i++;
	});
	
	return false;	
}

function removeParamColor(obj,min)
{
	var parent = $(obj).parent().parent();
	if ($(obj).parent().parent().find('li').length>1) {
		$(obj).parent().find('.addColor').removeClass('addColor');
		$(obj).parent().parent().find('.addColor').hide();
		$(obj).parent().parent().find('.addColor:last').show();
		$(obj).parent().remove();
	}
	else {
		$(obj).parent().parent().find('.twpColorpickers:last').css({backgroundColor:'#FFFFFF'}).attr('value','');
		$(obj).parent().parent().find('.addColor:last').show();
	}	

	var i = 0;
	$(obj).parent().parent().find('.removeColor').show();
	$(obj).parent().parent().find('.removeColor').each(function() {
		if (i<min) $(this).hide();
		i++;
	});
}

function addSearchField(name,text)
{		
	$('.'+name+':last').after('<div class="'+name+'">'+$('.'+name+':last').html()+'</div>');
	$('.'+name+':last').find('input[name='+name+'s[]]').attr('value',text);
	$('.add_'+name).hide();
	$('.add_'+name+':last').show();
	$('.'+name).each(function(index,elm){
		var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
		$(elm).children('.sessionLabel').attr('for', tmp);
		$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
		
	});
	hover_btn();
}

function removeSearchField(obj,name)
{
	if ($('.'+name).length>1)
	{
		$(obj).parent().parent().remove();
	}
	else
	{
		$(obj).prev().attr('value','#');
	}
	$('.add_'+name).hide();
	$('.add_'+name+':last').show();
	$('.'+name).each(function(index,elm){
		var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
		$(elm).children('.sessionLabel').attr('for', tmp);
		$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
		
	});
	hover_btn();
}

function addHighlight()
{	
	$('.twpHighlight:last').after('<li class="twpHighlight formLine">'+$('.twpHighlight:last').html()+'</li>');
	$('.twpHighlight:last').find('input:first').attr('value','');
	$('.add_highlight').hide();
	$('.add_highlight:last').show();	
	hover_btn();
}

function removeHighlight(obj)
{
	if ($('.twpHighlight').length>1)
	{
		$(obj).parent().parent().remove();
	}
	else
	{
		$(obj).prev().attr('value','');
	}
	
	$('.add_highlight').hide();
	$('.add_highlight:last').show();	
	hover_btn();
}

function addMessage(text)
{
	if (text!='' && $('.twpMessage').length==1 && $('.twpMessage:first').find('input[name=messages[]]').attr('value')=='')
	{
		$('.twpMessage:first').find('input[name=messages[]]').attr('value',text);
	}
	else
	{
		$('.twpMessage:last').after('<li class="twpMessage formLine">'+$('.twpMessage:last').html()+'</li>');
		$('.add_message').hide();
		$('.add_message:last').show();
		$('.twpMessage').each(function(index,elm){
			var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
			$(elm).children('.sessionLabel').attr('for', tmp);
			$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
			
		});
		
		$('.twpMessage:last').find('input[name=messages[]], input[name=chpInfo[]]').attr('value',text);
	}
	hover_btn();
}

function removeMessage(obj)
{
	if ($('.twpMessage').length>1)
	{
		$(obj).parent().parent().remove();
	}
	else
	{
		$(obj).prevAll('input').attr('value','');
	}
	
	$('.add_message').hide();
	$('.add_message:last').show();
	$('.twpMessage').each(function(index,elm){
		var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
		$(elm).children('.sessionLabel').attr('for', tmp);
		$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
		
	});
	hover_btn();
}

function addSponsor(url,preview,isFlv)
{
	if (url!='' && $('.twpSponsor:last').find('input[name=sponsors[]]').attr('value')=='' && $('.twpSponsor:last').find('input[name=sponsorFiles[]]').attr('value')=='')
	{
		$('.twpSponsor:last').find('input[name=sponsors[]]').attr('value',url);
		$('.twpSponsor:last').find('input[name=sponsorFiles[]]').hide();
					
		$('.twpSponsor:last').find('.preview').attr('href',url).show();
		$('.twpSponsor:last').find('.preview').find('img').attr('src',preview);	
		if (isFlv) $('.twpSponsor:last').find('.preview').attr('toptions','width = 400, height = 270');	
		else $('.twpSponsor:last').find('.preview').attr('toptions','');	
	}
	else
	{
		$('.twpSponsor:last').after('<li class="twpSponsor formLine">'+$('.twpSponsor:last').html()+'</li>');
		$('.twpSponsor:last').find('input[name=sponsors[]]').attr('value',url);		
		$('.twpSponsor:last').find('.preview').attr('href',url);
		$('.twpSponsor:last').find('.preview').find('img').attr('src',preview);
		if (isFlv) $('.twpSponsor:last').find('.preview').attr('toptions','width = 400, height = 270');	
		else $('.twpSponsor:last').find('.preview').attr('toptions','');
		
		if (url=='') {
			$('.twpSponsor:last').find('input[name=sponsorFiles[]]').show();
			$('.twpSponsor:last').find('.preview').hide();			
		}
		else {
			$('.twpSponsor:last').find('input[name=sponsorFiles[]]').hide();			
			$('.twpSponsor:last').find('.preview').show();			
		}
		
		$('.add_sponsor').hide();
		$('.add_sponsor:last').show();
		$('.twpSponsor').each(function(index,elm){
			var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
			$(elm).children('.sessionLabel').attr('for', tmp);
			$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
			
		});				
	}
	hover_btn();
}

function removeSponsor(obj)
{
	if ($('.twpSponsor').length>1)
	{
		$(obj).parent().parent().remove();
	}
	else
	{
		$(obj).prevAll('input').attr('value','');
		$('.twpSponsor:last').find('input[name=sponsorFiles[]]').show();
		$('.twpSponsor:last').find('.preview').hide();		
	}
	
	$('.add_sponsor').hide();
	$('.add_sponsor:last').show();
	$('.twpSponsor').each(function(index,elm){
		var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
		$(elm).children('.sessionLabel').attr('for', tmp);
		$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
		
	});
	hover_btn();
}

function addLevel(labelText,inputText)
{
	if (inputText!='' && $('.twpLevel').length==1 && $('.twpLevel:first').find('input[name=levels[]]').attr('value')=='')
	{
		$('.twpMessage:first').find('input[name=levels[]]').attr('value',inputText);
	}
	else
	{
		$('.twpLevel:last').after('<li class="twpLevel formLine">'+$('.twpLevel:last').html()+'</li>');
		$('.add_level').hide();
		$('.add_level:last').show();
		$('.twpLevel').each(function(index,elm){
			var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
			$(elm).children('.sessionLabel').attr('for', tmp);
			$(elm).children('.sessionLabel').find('span').html(labelText+' '+(index+1)+' :');
			$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
			
		});
		
		$('.twpLevel:last').find('input[name=levels[]]').attr('value',inputText+' '+$('.twpLevel').length);
	}
	hover_btn();
}

function removeLevel(obj)
{
	if ($('.twpLevel').length>1)
	{
		$(obj).parent().parent().remove();
	}
		
	$('.add_level').hide();
	$('.add_level:last').show();
	$('.twpLevel').each(function(index,elm){
		var tmp = $(elm).children('.sessionLabel').attr('for')+'-'+index;
		$(elm).children('.sessionLabel').attr('for', tmp);
		$(elm).children('.sessionInput').children('.sessionText').attr('id', tmp);
		$(elm).children('.sessionLabel').find('span').html($(elm).children('.sessionLabel').find('span').html().substring(0,$('.twpLevel').children('.sessionLabel:first').find('span').html().length-3)+(index+1)+' :');
	});
	hover_btn();
}

function selectLayout()
{
	var found = false; // try to find at least one value, to go to the next step (and open the modal box)
	
	$('input[name=hashtags[]]').each(function(){
		if (jQuery.trim($(this).attr('value'))!='' && jQuery.trim($(this).attr('value'))!='#') found = true;
	});
	$('input[name=twitterlists[]]').each(function(){
		if (jQuery.trim($(this).attr('value'))!='') found = true;
	});
	
	if (found)
	{			
		msg.dialog( "option", "width", $(window).width()-100 );
		msg.dialog( "option", "height", $(window).height()-50 );
		msg.dialog('open'); 
		$('body').css('overflow', 'hidden');
	}
	else
	{		
		$('#searchForm').submit();
	}
}

function selectLayoutOK(layoutId)
{	
	msg.dialog('close');
	$('#layoutId').attr('value',layoutId);
	$('#searchForm').submit();
	$('#searchForm').hide();
	$('#loadLayout').show();
	
}


function changeLayout()
{
	msg2.dialog( "option", "width", $(window).width()-100 );
	msg2.dialog( "option", "height", $(window).height()-50 );	
	$('body').css('overflow', 'hidden');
	msg2.dialog('open');
}
function sliderRange(){
	$('.range').each(function(i, elm){
		$(elm).click(function(){
			$('#amount').attr('value',$(elm).attr('title'));
			setPricing($(elm).attr('title'));
		});
	});
}
