var priceSelect = new Array();
var total;

// Initialize
$(function () {
  // This is solved at the php level (just keep it for a while)
  // Initialize radio buttons (if none is checked)
  //if ($('#rdo30days'))
  //if (!$('#rdo30days, #rdo60days').is(':checked')) $('#rdo30days')[0].checked = true;

  // New method for 'change' handler to country <select>
  $('#country').bind('change', function (e) {
    var selIdx = e.target.selectedIndex;
    var country = e.target.options[selIdx].text;
    switch (country) {
      case 'United States':
        if ($('#ca_state').children().length == 0) $('#showstate select').appendTo('#ca_state').val('');
        $('#us_state select').appendTo('#showstate');
        $('#state').show();
        break;
      case 'Canada':
        if ($('#us_state').children().length == 0) $('#showstate select').appendTo('#us_state').val('');
        $('#ca_state select').appendTo('#showstate');
        $('#state').show();
        break;
      default:
        if ($('#us_state').children().length == 0) $('#showstate select').appendTo('#us_state').val('');
        if ($('#ca_state').children().length == 0) $('#showstate select').appendTo('#ca_state').val('');
        $('#state').hide();
    }
  }).trigger('change');
  
  // 'change' handler to country <select>
/*  $('#countryxxx').bind('change', function (e) {
    var selIdx = e.target.selectedIndex;
    var country = e.target.options[selIdx].text;
    switch (country) {
      case 'United States':
        $('#state').show();
        $('#ca_state').hide().children().val('');
        $('#us_state').show();
        break;
      case 'Canada':
        $('#state').show();
        $('#us_state').hide().children().val('');
        $('#ca_state').show();
        break;
      default:
        $('#state').hide();
    }
  })
  .trigger('change');
  */
  // Restrict three choices to categories
  $('#category').bind('change', function (e) {
    if ($('#category option:selected').length > 3) {
      $('#category option').not(':selected:lt(3)').removeAttr('selected');
    }
    var str = '';
    if ($('#category option:selected').length > 0) str = 'You have selected,<br />';
    
    $('#category option:selected').each(function () {
      str += $(this).text() + '<br />';
    });
    
    $('#category_result').html(str);
  })
  .trigger('change');
  
  // Calculate total price each time clicked
  $('input.price').bind('click', function (e) {
    // Change behavior of enhanced/featured listing checkboxes so they work like radio buttons
    switch (e.target.id) {
      case 'chkEnh':
        $('#chkTop')[0].checked = false;
        break;
      case 'chkTop':
        $('#chkEnh')[0].checked = false;
        break;
    }
    calculateTotal();
  });
  
  // 'focus' and 'blur' handler to highlight the focused fields.
  $('input:text, select, textarea').bind('focus', function() {
    $(this).css('background-color', '');
    $(this).parent().parent('tr').css('background-color', '#ddf2f2');
    $(this).parent('div').parent().parent('tr').css('background-color', '#ddf2f2');
  });
  $('input:text, select, textarea').bind('blur', function() {
    $(this).parent().parent('tr').css('background-color', '');
    $(this).parent('div').parent().parent('tr').css('background-color', '');
  });
  
  calculateTotal();
});

// Calculate total price
function calculateTotal() {
  var prList = new Array();
  var sum;

  total = parseFloat($('#rdo30days').val());
  
  // Handle calculation for partners
  priceSelect[0] = 1;
  priceSelect[1] = $('#rdo60days')[0].checked ? 1 : 0;
  priceSelect[2] = $('#chkEnh')[0].checked ? 1 : 0;
  priceSelect[3] = $('#chkTop')[0].checked ? 1 : 0;
  
  $('.partnerPrices').each(function () {
    sum = 0;
    prList = $(this).children('.priceList').val().split(',');
    
    for (var i = 0; i < 4; i++) {
      sum += priceSelect[i] * prList[i];
    }
    
    $(this).children('input:checkbox').val(sum);
    $(this).children('.CobuyPrice').text(sum);
  });

  $('.price').not('#rdo30days').each(function () {
    if (this.checked) total += parseFloat($(this).val());
  });
  
  $('#total').text(total.toFixed(2));
}

function viewCart() {
  $('#xmode').val('viewcart');
  document.frmJobpost.submit();
}

function filter_html(html, tags) {
  if (!tags) tags = "a.*?|b.*?|br.*?|em.*?|h[1-6].*?|i.*?|img.*?|p.*?|strong.*?|table.*?|td.*?|th.*?|tr.*?|ul.*?|ol.*?|li.*?";
  var regex1 = new RegExp("&lt;(" + tags + ".*?)&gt;", "ig");
  var regex2 = new RegExp("&lt;\/(" + tags + ")&gt;", "ig");
  
  // why should there be a null character 
  html = html.replace(/\0/g, ''); 
  // convert the ampersants to null characters 
  html = html.replace(/\&/g, '\0');
  // convert the sharp brackets to there html code 
  html = html.replace(/</g, '&lt;');
  html = html.replace(/>/g, '&gt;');
  // restore the tags that are concidered safe 
  if (tags) { 
    html = html.replace(regex1, '<$1>');
    html = html.replace(regex2, '</$1>');
  } 
  // restore the ampersants 
  html = html.replace(/\0/g, '&', html); 
 
  return html; 
}

// Check form submission
function checkPostSubmission(btn) {
  var ok = true;
	var test = '';
	$('table.job_post input:text, table.job_post textarea, table.job_post select').each(function () {
		if (this.parentNode.style.display != 'none') {
		if ($.trim(this.value) == '') {
			$(this).css('background-color', '#fdd');
			ok = false;
		}
		else {
			$(this).css('background-color', '');
		}}
	});
  
  if (ok) {
    switch (btn) {
      case 'preview':
        //$('#xmode').val('preview');
        
        var postData = {
          xmode: 'preview',
          title: filter_html($('#title').val(), 'allow_notags'),
          company: filter_html($('#company').val(), 'allow_notags'),
          description: filter_html($('#description').val(), null),
          city: filter_html($('#city').val(), 'allow_notags'),
          state: $('#showstate').children('select').val(),
          country: $('#country').val()
        };
        
        $('#previewPane').load('preview', postData, function () {
          tb_show('Preview Job Posting', '#TB_inline?height=650&width=800&inlineId=previewPane', false);
          //return false;
        });
      
        // document.frmJobpost.action = 'preview';
      	// document.frmJobpost.target = '_blank';
      	// document.frmJobpost.submit();
      	// document.frmJobpost.action = '';
      	// document.frmJobpost.target = '_self';
        
        break;
      case 'addmore':
        $('#xmode').val('addmore');
        break;
      case 'review':
        $('#xmode').val('review');
        break;
      default:
        $('#xmode').val('review');
    }
  }
  
  if (ok) {
    // Empty hidden states so avoid name conflicts
    $('#us_state, #ca_state').empty();
  }
  else {
    alert('Please fill all the required fields.'+test);
  }
  return ok;
}
