$(document).ready(function()
{
  window._shopVisibleLinesQuantity = 2;
  $('#shop-tabs').tabs({click:validateTab});
  
  //buttons
  $('#but-payment').click(paymentOnline);
  $('.valider').click(tabNext);
  $('.back').click(tabPrev);
  $('.home').click(function(){location.href = "accueil";});
  
  //adv lines
  $('#shop-line-add').click(shopAddLine);
  $('#shop-line-del').click(shopDelLine);

  //sections/subsections  
  shopUpdateSubSection();
  $('#shop-parent-section').change(function () {shopUpdateSubSection(); validateOptions(); });
  
  //order recap page
  $('#shop-customer INPUT').blur(shopRecapCustomer);
  $('#shop-child-section').change(shopRecapSection);
  $('#shop-options INPUT:checkbox').change(function(){validateOptions();shopRecapOptions();});
  $('#shop-period INPUT:radio').change(shopRecapPeriod);
  shopRecapPeriod();
  $('#shop-adv INPUT:text').blur(shopRecapAdv);
  
  $('.jqmWindow').jqm({modal: true, onHide: uploadValidate});
  
  $('#upload-form').ajaxForm(
  { 
	  dataType:  'json', 
    success:   uploadResult
  });

	$('#upload-del').click(function()
	{  
  	$.ajax(
	  {
	    type: "GET",
	    url: "index.php?app=shop&event=upload_del",
	    success: function(){
	    	$('#upload-img').remove();
	    	$('#upload-del').css('display', 'none');
	    	$('#shop-option-7').attr('checked', '');
	    	shopRecapOptions();
	    },
	    error: function () { alert('Ajax error!'); }
	 	});
	});
	
	$('#shop-option-7').click(function()
	{
		if ($(this).attr('checked') == true)
			$('#upload-div').jqmShow();
	});
	 
});

function uploadResult (json)
{
	if (json.error != '') alert(json.error);
	if (json.img != '')
	{
		$('#upload-img').remove();
		$('#upload-form').after('<img id="upload-img" src="' + json.img + '" alt="" />');
		$('#upload-del').css('display', 'inline');
		$('#shop-option-7').attr('checked', 'checked');
		shopRecapOptions();
	}
}

function uploadValidate (hash)
{
	if ($('#upload-del').css('display') == 'none')
	{
		$('#shop-option-7').attr('checked', '');
	}
	else
	{
		$('#shop-option-7').attr('checked', 'checked');
	}
	hash.w.hide();
	hash.o.remove();
}

function tabNext ()
{
  var i = $('#shop-tabs').tabsSelected();
  if (i < 5)
  {
    $('#shop-tabs').tabsClick(i + 1);
  }
}

function tabPrev ()
{
  var i = $('#shop-tabs').tabsSelected();
  if (i > 1)
  {
    $('#shop-tabs').tabsClick(i - 1);
  }
}

function tab (i)
{
  if (i > 1 && i < 5)
  {
    $('#shop-tabs').tabsClick(i);
  }
}

function validateTab (clicked, show, hide)
{
	var cur_tab = $(hide).attr('id');
  var new_tab = $(show).attr('id');
	if (new_tab != 'shop-page0' && new_tab != 'shop-page1') //Vos coordonnées
	{
		var err = false;
		//check personal info fields
		$('#shop-customer INPUT').each(function ()
		{
			if ($(this).attr('name') == 'addr2') return; //not mandatory field
			if ($(this).val() == '')
			{
				err = true;
				$(this).addClass('error');
			}
			else
				$(this).removeClass('error');
		});
		
		if (err)
		{
			alert('Merci de remplir les champs requis.');
			tab(2);
			return false;
		}
		
		//check email
		var email = $("#shop-customer INPUT[name='email']");
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test(email.val()))
		{
			email.addClass('error');
			alert('Email is incorrect.');
			tab(2);
			return false;
  	}
  	else
  	{
  		email.removeClass('error');
  	}
	}
	
	if (new_tab != 'shop-page0' && new_tab != 'shop-page1' && new_tab != 'shop-page2') //Détails de l'annonce
	{
		//check adv lines
		var empty = false;
		$("#shop-adv P:visible INPUT").each(function()
		{
			if ($.trim($(this).val()) == '')
			{
				empty = true;
				$(this).addClass('error');						
			}
			else
				$(this).removeClass('error');
		});

		if (cur_tab == 'shop-page2' && empty == true && false == confirm('You are going to pay for empty lines. Are you sure?'))
		{
			tab(3);
			return false;
		}
	}
	
	return true;
}

function validateOptions ()
{
	if (!window._shopParentSection) window._shopParentSection = 0;
	
	//if (-1 != jQuery.inArray($('#shop-parent-section').val(), cats_domi))
	if ($('#shop-parent-section').val() == '59')
		$('#shop-option-4').attr('checked', 'checked');
	else if (window._shopParentSection == '59')
		$('#shop-option-4').attr('checked', '');
	
	window._shopParentSection = $('#shop-parent-section').val();
}

function shopAddLine (event)
{
  if (window._shopVisibleLinesQuantity == 6) return;
  $('#shop-line-del').css('display', 'inline');
  window._shopVisibleLinesQuantity++;
  $('#shop-line' + window._shopVisibleLinesQuantity).show();
  $('#shop-line' + window._shopVisibleLinesQuantity + '-recap').show();
  if (window._shopVisibleLinesQuantity == 6) $(event.target).hide();
  
  recalcPrice();
  
  return false;
}

function shopDelLine (event)
{
  if (window._shopVisibleLinesQuantity == 2) return;
  $('#shop-line' + window._shopVisibleLinesQuantity).hide();
  $('#shop-line' + window._shopVisibleLinesQuantity + ' INPUT').val('');
  $('#shop-line' + window._shopVisibleLinesQuantity + '-recap').hide();
  $('#shop-line' + window._shopVisibleLinesQuantity + '-recap SPAN.txt').html('');
  window._shopVisibleLinesQuantity--;
  $('#shop-line-add').css('display', 'inline');
  if (window._shopVisibleLinesQuantity == 2) $(event.target).hide();
  
  recalcPrice();
  
  return false;
}

function shopUpdateSubSection ()
{
  var id_section_parent = $('#shop-parent-section').val();
  $('#shop-child-section').children().remove();
  var kids = window._shopSubSections[id_section_parent];
  $(kids).each(function(index, value)
  {
    var opt = document.createElement('OPTION');
    $(opt).attr('value', value.id_section);
    $(opt).html(value.title);
    $('#shop-child-section').append(opt);
  });
  //update text on order recap page
  shopRecapSection();
  
  recalcPrice();
}

function shopRecapSection ()
{
  $('#shop-recap-parent-section').html($('#shop-parent-section OPTION:selected').text());
  $('#shop-recap-child-section').html($('#shop-child-section OPTION:selected').text());  
}

function shopRecapCustomer (event)
{
  var field = $(event.target);
  $('#shop-recap-' + field.attr('name')).html(field.val());
}

function shopRecapOptions ()
{
  var i = 0;
  $('#shop-recap-options SPAN[class!=field]').hide();
  $('#shop-options INPUT:checked').each(function()
  {
    $('#shop-recap-options SPAN#' + $(this).attr('id') + '-recap').css('display', 'block');
    i++;
  });
  if (i == 0) $('#shop-recap-options SPAN#shop-option-0-recap').css('display', 'inline');
  
  //photo recap
  if ($('#upload-img').attr('id') != 'undefined')
	  $('#shop-recap-options SPAN#shop-option-7-recap').html('<img src="' + $('#upload-img').attr('src') + '" alt="" />');
  else
	  $('#shop-recap-options SPAN#shop-option-7-recap').html('');
  
  recalcPrice();
}

function shopRecapPeriod ()
{
  $('#shop-recap-period SPAN[class!=field]').html($('#shop-period INPUT:checked + SPAN').html());
  recalcPrice();
}

function shopRecapAdv (event)
{
  var src = $(event.target);
  $('#shop-' + src.attr('name') + '-recap SPAN.txt').html(src.val());
}

function recalcPrice ()
{
  var priceSection = getFloat(_priceSection[$('#shop-parent-section').val()][$('#shop-period INPUT:checked').val()]);
  var priceOption = 0;
  $('#shop-options INPUT:checked').each(function()
  {
    priceOption += getFloat(_priceOption[$(this).val()][$('#shop-period INPUT:checked').val()]);
  });
  var linesQuant = window._shopVisibleLinesQuantity;
  //var price_ht = priceSection * linesQuant + priceOption;
  //var price_tva = price_ht * 0.196;
  //var price_ttc = price_ht + price_tva;
  //$('#price_ht').html(price_ht.toFixed(2).toString() + ' €');
  //$('#price_tva').html(price_tva.toFixed(2).toString() + ' €');
  //$('#price_ttc').html(price_ttc.toFixed(2).toString() + ' €'); 
  var price_ttc = priceSection * linesQuant + priceOption;
  $('#price_ttc').html(price_ttc.toFixed(2).toString() + ' €'); 
}

function getFloat (str)
{
  var f = parseFloat(str);
  return (isNaN(f)) ? 0 : f;
}

function paymentOnline ()
{
	//show ajax loader
	$('BODY').append('<div class="ajax-loader"></div>');
  $('DIV.ajax-loader').css('height', $('#bl-top').height()); //fix for IE6
	
	//send order, ajax
	$.ajax(
	{
  	type: "POST",
   	url: "index.php?app=shop&event=order_save",
    data: $('#shop-form').formSerialize() + "&l=" + window._shopVisibleLinesQuantity,
   	success: function(msg){
   		$('DIV.ajax-loader').remove();
    	if (msg != '')
    	{
    		tabNext();
    		$('#form-paypal-div').html(msg);
    		//if ($('#form-paypal'))
	    		//$('#form-paypal').submit();
    	}
    	//else
    	//	alert(msg);
   	},
   	error: function () { $('DIV.ajax-loader').remove();	}
 });
	
 return false;
}