﻿/**
 * Created by IntelliJ IDEA.
 * User: nunoaguiar
 * Date: 29/Nov/2010
 * Time: 16:05:06
 * To change this template use File | Settings | File Templates.
 */

var VALID_PHONE_CHARS = "()-+. 0123456789",
    MIN_PHONE_DIGIT = 9;

$( document ).ready( function() {
  if( $( 'table#showCartTable' ).length != 1 )
    $( '.OrderLinePhotoWrapper:first, .OrderLineData:first, .deleteOrderLineCol:first' ).css( 'padding-top', '0' );

  if( $( 'form#paymentMethod' ).length )
    $( '.paymentMethodHolder tr:first-child td' ).css( 'padding-top', '0' );

  if( $( 'form#SearchResultsForm' ).length == 0 )
    $( '#newSearchHolder' ).css( 'display', 'block' );

  /* if there's only one gateway option, preselect it by default */
  if( $( 'table.paymentMethodHolder' ).length ) {
    if( $( '.paymentMethodHolder .paymentMethodDescription' ).length == 1 )
      $( 'input[type=radio][name=EcomCartPaymethodID]' ).attr( 'checked', 'checked' );
  }

  if( $( '.UnitIntroduction a' ).length ) {
    $( '.UnitIntroduction a' ).click( function() {
      $( this ).parent().next().slideToggle();
      $( this ).parent().find( 'a' ).toggle();
    });
  }
});

String.prototype.replaceAt=function(index, char) {
  return this.substr(0, index) + char + this.substr(index+char.length);
}
 
function adjustPricePerNight(newPrice, unitID) {
  var PricePerNight = 0;
  newPrice = newPrice.substring(0,newPrice.length-1);
  newPrice = newPrice.replace(/\./g, ",");
  newPrice = newPrice.replaceAt(newPrice.lastIndexOf(","), ".");
  newPrice = newPrice.replace(/\,/g, "");
  PricePerNight = newPrice/PostedNumberOfDays;
  $("#PriceNight" + unitID).html(PricePerNight.toFixed(2) + "€"); 
}

function checkValidChars( str, validChars ) {
  var c;

  for( var i = 0; i < str.length; i++ ) {
    c = str.charAt( i );

    if( validChars.indexOf( c ) == -1 ) {
      return false;
    }
  }
  return true;
}



/* checks if the user has selected a gateway and if so, sends the gateway's image to the next step so that the
 * image is shown. If no gateway is selected, an error message is shown */
function gatewaySelected( errorMsg ) {
  var selectedRadio = $("input[name=EcomCartPaymethodID]:checked");
  if( selectedRadio.length == 1 ) {
    var hiddenInputIconUrl = $( selectedRadio ).parent().next().find( 'input[name=payMethodImg]' );

    if( hiddenInputIconUrl.length == 1 )
      $( hiddenInputIconUrl ).val( $( hiddenInputIconUrl ).prev().attr( 'src' ) );
    return true;
  }
  else {
    alert( errorMsg );
    return false;
  }
}



/* validates the client data form */
function validateForm( incompleteFieldsMsg, incorrectMailMsg, incorrectPhoneMsg, incorrectCellPhoneMsg, countryNotSelectedMsg ) {
  var field,
      errorMsg = "",
      fieldValue = "",
      formCorrect = true,
      incompleteFieldsMsgIncluded = false,
      incorrectMailMsgIncluded = false,
      incorrectPhoneMsgIncluded = false,
      incorrectCellPhoneMsgIncluded = false,
      countryNotSelectedMsgIncluded = false;

  $( 'label.mandatory' ).each( function() {
    field = $( this ).parent().next().find( 'input' );

    if( field.length == 0 )
      field = $( this ).parent().next().find( 'select' );

    fieldValue = $( field ).val();

    /* check if the field has any value after removing all the white spaces */
    if( fieldValue.replace(/^\s*|\s*$/g,'').length == 0 ) {
      field.addClass( 'redBorder' );

      /* add the incomplete fields message if it hasn't been added yet */
      if( !incompleteFieldsMsgIncluded ) {
        errorMsg = incompleteFieldsMsg + "\n" + errorMsg;
        incompleteFieldsMsgIncluded = true;
        formCorrect = false;
      }
    }
    else {
      field.removeClass( 'redBorder' );

      if( $( this ).attr( 'for' ) == "EcomOrderCustomerEmail" ) {
        /* e-mail not valid */
        if( !validateEmail( fieldValue ) ) {

          /* add the incorrect e-mail message if it hasn't been added yet */
          if( !incorrectMailMsgIncluded ) {
            errorMsg += incorrectMailMsg + "\n";
            incorrectMailMsgIncluded = true;
            formCorrect = false;
          }
          field.addClass( 'redBorder' );
        }
        else
          field.removeClass( 'redBorder' );
      }

      if( $( this ).attr( 'for' ) == "EcomOrderCustomerPhone" ) {
        /* if the phone number has invalid characters or not enough digits and the incorrect phone message hasn't been added yet then add it */
        if( fieldValue.length < MIN_PHONE_DIGIT || !checkValidChars( fieldValue, VALID_PHONE_CHARS ) && !incorrectPhoneMsgIncluded ) {
          errorMsg += incorrectPhoneMsg + "\n";
          incorrectPhoneMsgIncluded = true;
          formCorrect = false;
          field.addClass( 'redBorder' );
        }
        else
          field.removeClass( 'redBorder' );
      }
 
      if( $( this ).attr( 'for' ) == "EcomOrderCustomerCell" ) {
        /* if the cell-phone number has invalid characters or not enough digits and the incorrect cell-phone message hasn't been added yet then add it */
        if( fieldValue.length < MIN_PHONE_DIGIT || !checkValidChars( fieldValue, VALID_PHONE_CHARS ) && !incorrectCellPhoneMsgIncluded ) {
          errorMsg += incorrectCellPhoneMsg + "\n";
          incorrectCellPhoneMsgIncluded = true;
          formCorrect = false;
          field.addClass( 'redBorder' );
        }
        else
          field.removeClass( 'redBorder' );
      }

      if( $( this ).attr( 'for' ) == "EcomOrderCustomerCountry" && fieldValue == "nothing" ) {
        if( !countryNotSelectedMsgIncluded ) {
          errorMsg += countryNotSelectedMsg;
          countryNotSelectedMsgIncluded = true;
          formCorrect = false;
          field.addClass( 'redBorder' );
        }
        else
          field.removeClass( 'redBorder' );
      }
    }
  });

  if( !formCorrect )
    alert( errorMsg );
  
  return formCorrect;
}
