
/*
    WALIDACJA POL FORMULARZA
 */

function validateForm( idScope ) {

    if ( idScope == null ) return false;

    var items = $( '#' + idScope ).find( "input.text_input" );

    for( var i = 0 ; i < items.length ; i++ ) {

        var itemClass = $(items[i]).attr( "class" );

        if ( itemClass.indexOf( "hide" ) >= 0 )
            continue;

        var result = $(items[i]).attr('onchange')();

        if ( !result ) {
            focus( $(items[i]).attr('id') );
            return false;
        }

    }

    return true;

}

function validateField( id, validateCondition, validationType, minLength, maxLength, validateWith ) {

    if ( id == null || validationType == null ) return false;

    if ( validateCondition != null ) {
        var separatorIndex = validateCondition.indexOf('=');
        if ( separatorIndex > 0 ) {
            var conditionId = validateCondition.substr(0,separatorIndex);
            var expectedValue = validateCondition.substr(separatorIndex+1);

            if ( $('#'+conditionId).val() != expectedValue ) return true;
        }
    }

    var partResult = true;

    if ( validateWith != null && validateWith != '' )
        partResult = compareStrings( validateWith, id, true );

    if ( validationType == 'login' )
        return partResult && validateLogin( id );

    else if ( validationType == 'email' )
        return partResult && validateEmail( id );

    else if ( validationType == 'anyString' )
        return partResult && validateString( id, minLength, maxLength );

    else if ( validationType == 'number' )
        return partResult && validateNumber( id, minLength, maxLength );

    else if ( validationType == 'postCode' )
        return partResult && validatePostCode( id );

    else if ( validationType == 'searchValue' )
        return partResult && validateSearchValue( id );

    return false;
    
}

function validateLogin(id) {

    var login = $('#'+id).val();

    var loginOk = validateLoginFormat( login );

    setToolTipData( id, loginOk, 'Login OK', 'Niepoprawny login. Musi składać się z kombinacji przynajmniej 3 liter, cyfr lub znaków @_.' );

    return loginOk;

}

function validatePassword(id) {

    var password = $('#' + id ).val();

    var passwordOk = validatePasswordFormat( password );

    setToolTipData( id, passwordOk, 'Hasło OK', 'Niepoprawne hasło. Musi składać się z kombinacji przynajmniej 5 znaków' );

    return passwordOk;

}

function validateEmail(id) {

    var email = $('#'+id).val();

    var emailOk = validateEmailFormat(email);

    setToolTipData( id, emailOk, 'Adres email OK', 'Adres email ma niepoprawny format' );

    return emailOk;
    
}

function validateNumber(id, min, max) {

    var number = $('#'+id).val();

    var numberOk = validateNumberFormat(number,min,max);

    setToolTipData( id, numberOk, 'OK', 'Wprowadzone dane mają niepoprawny format' );

    return numberOk;

}

function validatePostCode(id) {

    var postCode = $('#'+id).val();

    var postCodeOk = validatePostCodeFormat(postCode);

    setToolTipData( id, postCodeOk, 'Kod pocztowy jest poprawny', 'Kod pocztowy ma niepoprawny format' );

    return postCodeOk;

}

function validateSearchValue(id) {

    var searchValue = $( '#' + id ).val();
    searchValue = searchValue.toLowerCase();
    searchValue = searchValue.replace( /[^a-z0-9ąęźłóćń]/g, '' );

    return validateStringFormat( searchValue, 3, 50 );

}

function validateString(id, min, max) {
    
    var txt = $('#'+id).val();

    var txtOk = validateStringFormat(txt,min,max);

    setToolTipData( id, txtOk, 'OK', 'Wprowadzone dane mają niepoprawny format');

    return txtOk;
    
}

function validateCheckbox(id, need, errorString) {

    var checked = $('#'+id).is(':checked');
    if ( checked ) $('#'+id).val('true');
    else $('#'+id).val('false');
    if( need ) {
        if ( checked )
            setToolTipInfo( id, 'ok', 'OK');
        else {
            if ( errorString == null ) errorString = 'Zgoda musi zostać zatwierdzona';
            setToolTipInfo( id, 'error', errorString );
            return false;
        }
    }
    return true;
}


/*
    POROWNYWANIE LANCUCHOW ZNAKOWYCH

 */

function isEmpty( txt ) {
    return txt == null || txt.length == 0;
}

function validateStringFormat( txt, minLength, maxLength ) {

    if ( minLength != null && minLength != '' ) {

        if ( txt == null ) return false;

        if ( txt.length < minLength ) return false;

    }

    if ( txt != null && maxLength != null && maxLength != '' ) {

        if ( txt.length > maxLength ) return false;

    }

    return true;

}

function compareStrings( first, second, showError ) {

    var s1 = $('#'+first).val();
    var s2 = $('#'+second).val();

    if ( s1 == s2 ) {
        if ( showError ) setToolTipInfo( second, 'ok', 'Potwierdzenie zgadza się z oryginałem');
        return true;
    }
    else if ( showError ) setToolTipInfo( second, 'error' , 'Potwierdzenie nie zgadza się z oryginałem');
    
    return false;
}

/*
    FUNKCJE POMOCNICZE
 */

function formatAmount( amount ) {

    var amountStr = amount.toFixed(2).replace('.',',');
    amountStr = insertSpace( amountStr, "," );
    amountStr = insertSpace( amountStr, " " );
    return amountStr + ' zł';
}

function insertSpace( amount, delimiter ) {

    var comaIndex = amount.indexOf( delimiter );
    if ( comaIndex > 3 ) amount = amount.substring( 0, comaIndex - 3 ) + " " + amount.substring( comaIndex - 3 );
    return amount;

}

function press( event, id, anyKey ) {

    if ( ( anyKey || event.keyCode == 13 ) && id != null )
        $('#'+id).click();

    return true;

}

function focus( id ) {
    $('#'+id).focus();

}

function submitOnConfirm( idForm, question ) {

    if ( confirm(question) )
        $('#'+idForm).submit();

}

/*
    FORMULARZE
 */

function focusInput( object ) {
    $(object).addClass( 'focused' );
}
function blurInput( object ) {
    $(object).removeClass( 'focused' );
}

function showOptions( object ) {
    $(object).parent().next().toggle('fast');
    $('#facebox').click( hideOptions );
}
function hideOptions() {
    $('#facebox').find('.input_options').hide();
}
function selectOption( obj, id_selection, value ) {
    $('#facebox').unbind('click');
    $('#'+id_selection).val( value );
    $('#'+id_selection+"_select").next().hide('fast');
    $('#'+id_selection+"_select").find('.select_input').html( $( obj ).html() );
}

/*
    WYRAZENIA REGULARNE
 */

function validateLoginFormat( login ) {

    if ( login == null ) return null;

    return login.match( /^[\w\.@]{3,}$/ );

}

function validatePasswordFormat( password ) {

    if ( password == null ) return null;

    return validateStringFormat( password , 5 , 30 );

}

function validateEmailFormat( email ) {

    if ( email == null ) return null;

    return email.match( /^[\w\.-]+@([\w-]{2,}\.)+([\w]{2,4})$/ );

}

function validatePostCodeFormat( postCode ) {

    if ( postCode == null ) return null;

    return postCode.match( /^[0-9]{2}-[0-9]{3}$/ );

}

function validateNumberFormat( number, min, max ) {

    if ( number == null ) return false;

    var lengthOk = validateStringFormat( number , min , max );

    return lengthOk && number.match( /^[0-9]*$/ );
}

/*
    OPERACJE NA KODZIE HTML
 */

function openStatusPopup( statusClass, txt, reload, newPageUrl ) {
    
    $('#panel_status_icon').removeAttr('class');
    $('#panel_status_icon').addClass( statusClass );
    $('#panel_status_icon').addClass( 'first' );
    $('#panel_status_message').html(txt);
    $('#panel_status_reload').html( reload.toString() );
    $('#panel_status_redirect_page').html( newPageUrl );

    jQuery.facebox( $('#panel_status').html() );

    $('#facebox .confirmButton').focus();

}

function newClick( e ) {
    if ( e.keyCode == 13 ) {
        $.facebox.close();
        $(document).trigger('close.facebox');
    }
}

function setToolTipData( id, isOk, textOk, textError ) {

    var type = 'ok';
    var text = textOk;

    if ( !isOk ) {
        type = 'error';
        text = textError;
    }

    setToolTipInfo( id, type, text );

}
function setToolTipInfo( id, type, text ) {

    $('#'+ id + '_tooltip' + ' a div').removeAttr('class');
    $('#'+ id + '_tooltip' + ' a div').addClass(type + ' fleft');
    $('#'+ id + '_tooltip' + ' a span').html(text);

}

function switchFormData( panelClass, toOn, animate ) {

    var idOn = '.' + toOn + '_describer';

    var displayVal = $(idOn).css('display');

    if ( displayVal == null || displayVal == 'none' ) {

        $( '.person_describer' ).css('display','none');
        $( '.firm_describer' ).css('display','none');

        $(idOn).css('display','table-row');

    }
    
    $('#'+panelClass).val( toOn );
    $('#r_'+toOn).attr('checked','checked');

}

function switchFVatData( toOn, animate ) {
    $('#binvoice').val(toOn);
    if ( toOn ) {
        $( '#fvat_data' ).fadeIn('slow');
        $( '#agree_fvat').attr('checked','checked');
    }
    else {
        if (animate)
            $( '#fvat_data' ).fadeOut('slow');
        else
            $( '#fvat_data' ).hide();
        $( '#disagree_fvat').attr('checked','checked');
    }
}

function selectCheckbox( id, select ) {
    if ( select ) $('#'+id).attr('checked','checked');
    $('#'+id).val(select);
}

function bindMenu() {
    function menuFlow() {
        $(this).parent().next().toggle('fast');
        if ( $(this).parent().attr('class').indexOf('closed') >= 0 ) {
            $(this).parent().removeClass('closed');
            $(this).parent().addClass('opened');
        }
        else {
            $(this).parent().removeClass('opened');
            $(this).parent().addClass('closed');
        }
    }
    $(document).ready( function() {
        $('#split_menu .opened .txt').click( menuFlow );
        $('#split_menu .closed .txt').click( menuFlow );
    });
}

function bindOrdersExtend() {

    function closeAllOrders() {
        $('.close_child').next().hide();
        $('.close_child').addClass('open_child');
        $('.close_child').removeClass('close_child');
    }
    function extendOrder() {
        //zamkniecie wszystkich otwartych pozycji
        closeAllOrders();
        //otwarcie kliknietej pozycji
        $(this).parent().addClass('close_child');
        $(this).parent().removeClass('open_child');
        $(this).parent().next().show();
    }
    $(document).ready( function() {
        $('.list_item .extend').click( extendOrder );
    });
}

var timerId = 0;

function attachSlideSwitch() {
    $(function() {
        timerId = setInterval( "slideSwitch()", 6000 );
    });
}

function slideSwitch() {
    var $active = $('#image_panel img.active');

    if ( $active.length == 0 ) $active = $('#image_panel img:first');

    var $next =  $active.next().length ? $active.next() : $('#image_panel img:first');

    $active.addClass('last-active');
    $('.our_best_link').removeClass('selected');

    $('#'+$next.attr('id')+'_link').addClass('selected');

    $next.css({opacity: 0.0})
        .removeClass('hide')
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

function attachSlideManualSwitch() {
    $('.our_best_link').click(function() {
        clearInterval(timerId);
        $('#image_panel img').removeClass('active last-active hide');
        $('.our_best_link').removeClass('selected');
        $(this).addClass('selected');
        $('#img_'+$(this).html()).addClass('active');
        attachSlideSwitch();
    });
}

