/**
     *  Zobrazeni loaderu ve vybranem boxu
     */

function showLoader( sBox ) {

    sLoad = '<img src=\"/public/images/loader.gif\" />';
    handleContentData( sLoad, sBox );

}



/**
     *  Funkce pro presmerovani
     */

function redirectURL( sURL ) {

    document.location.href = sURL;

}
    
    
/**
     *  Funkce pro potvrzeni presmerovani
     */	     
     
function confirmLink( theLink, theMessage ) {

    if ( typeof( window.opera ) != 'undefined' ) {
        return true;
    }

    var is_confirmed = confirm( theMessage );
    if ( is_confirmed == true ) {
        return showContent( theLink, 'level3' );
    }
    return is_confirmed;

}
    
    
    
/**
     * Funkce pro nastaveni ID casti z adresy
     */

function setPartID( sUrl ) {

    sUrlRaw = $.url.setUrl(sUrl).attr("path");
    aUrl    = sUrlRaw.split( '/' );

    sPart    = aUrl[1];
    sPart   += '_';
    sPart   += ( aUrl.length > 2 && aUrl[2] != '' ) ? aUrl[2] : 'index';
    sPart   += '_';
    sPart   += ( aUrl.length > 3 && aUrl[3] != '' ) ? aUrl[3] : 'index';

    return sPart;

}



/**
     * Funkce pro nastaveni ID casti z adresy
     */

function setUrl( sUrl ) {

    sUrlRaw = $.url.setUrl(sUrl).attr("path");
    aUrl    = sUrlRaw.split( '/' );

    sPart    = '/';
    sPart   += aUrl[1];
    sPart   += ( aUrl.length > 2 && aUrl[2] != '' ) ? '/' + aUrl[2] : '';
    sPart   += ( aUrl.length > 3 && aUrl[3] != '' ) ? '/' + aUrl[3] : '';

    return sPart;

}



/**
     * Funkce pro nastaveni ID casti z adresy
     */

function setBaseUrl( sUrl ) {

    sUrlRaw = $.url.setUrl(sUrl).attr("path");
    aUrl    = sUrlRaw.split( '/' );

    sPart    = '/';
    sPart   += aUrl[1];
    sPart   += ( aUrl.length > 2 && aUrl[2] != '' ) ? '/' + aUrl[2] : '';

    return sPart;

} 
    
    
    
/**
     *  Funkce pro trideni tabulek
     *
     */	 	     
     
function sortTableItems( sUrl, sort ){
     
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );
     
    sBox = 'pContent_';

    showLoader( sBox );

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( sUrl ),
        data: sort,
        success: function ( data ) {
            handleContentData( data, sBox );
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
        }
    });

    return false;
     
}



/**
     *  Nacteni vybrane URL a vlozeni obsahu teto URL do vybraneho boxu
     */

function showContent( sUrl, sLevel ) {

/*

        $.cookie( 'sUrl', sUrl );
        $.cookie( 'sPartID', setPartID( sUrl ) );
		$.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

        sBox = 'pContent_' + sLevel;

        showLoader( sBox );

        $.ajax({
            url: setURL( sUrl ),
            success: function ( data ) {
                handleContentData( data, sBox );
            },
            error: function ( error ) {
                console.error ( 'Error: ', error );
            }
        });

        return false;
*/
}



/**
     *  Funkce pro nacteni adresy
     */

function baseUrl( sUrl ) {

    aUrlRaw = sUrl.split( 'http://' + location.hostname );
    aUrl    = aUrlRaw[1].split( '/' );

    sUrlNew = '/' + aUrl[1] + '/' + aUrl[2]

    return sUrlNew;

}



/**
     *  Nacteni vybrane URL a vlozeni obsahu teto URL do vybraneho boxu
     */

function showForm( sUrl, sLevel ) {
/*
        $.cookie( 'sUrl', sUrl );
        $.cookie( 'sPartID', setPartID( sUrl ) );
		$.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

        sBaseUrl  = baseUrl( sUrl );

        sBox = 'pContent_' + sLevel;

        showLoader( sBox );

        $.ajax({
            url: setURL( sUrl ),
            success: function ( data ) {
                handleContentData( data, sBox );
                renderFormAjax( sBaseUrl + '/renderAjax' );
            },
            error: function ( error ) {
                console.error ( 'Error: ', error );
            }
        });

        return false;
*/
}



/**
     *  Nacteni vybrane URL a vlozeni obsahu teto URL do vybraneho boxu
     */

function renderFormAjax( sUrl ) {
    
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

    $.ajax({
        url: setURL( sUrl ),
        dataType: 'script'
    });

    return false;

}



/**
     *  Vlozeni zvolenych dat v HTML do vybraneho boxu
     */

function handleContentData( sData, sBox ) {

    $( '#' + sBox ).html( sData );

}



/**
     *  Zpracování formulare
     */

function processForm( cForm, sUrl, sRedirectURL ) {
    
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();
    sBoxError = "bFormError";

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( sUrl ) + '&doAction=validate',
        data: sData,
        success: function ( msg ) {

            if ( msg == false ) {

                if ( sUrl == false ) {
                    cForm.submit();
                } else {
                    sendForm( sData, sUrl, sRedirectURL );
                }
            } else {

                clearFormErrors( cF.formToArray() );
                showFormError( msg );
            }

        }
    });

    return false;

}
    
    
/**
     *  Funkce pro odeslani formulare pro pridani prihozu
     */	     
     
function validateAuctionBid( cForm, sUrl, sRedirectURL ){
        
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );
		
    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( sUrl ) + '&doAction=validate',
        data: sData,
        success: function ( msg ) {
            
            if( msg != false ){
                $(document).ready(function(){
                    var message = showAuctionBidError( msg );
                    $("#example").html( message );
						
                    $("#example").dialog();
                    if( !$("#example").dialog( "isOpen" )  ){
                        $("#example").dialog( "open" );
                    }
                });

            }else{
                confirmAuctionBid( cForm, sUrl, sRedirectURL );
            }

        }
    });

    return false;
		
}


/**
     *  Funkce pro odeslani formulare pro pridani prihozu
     */

function validateBuyNow( cForm, sUrl, sRedirectURL ){

    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();

    var condition;
    if( $('#condition').length ){
        if( $('#condition').is(':checked') ){
            condition = 1;
        }else{
            condition = 0;
        }
    }else{
        condition = 0;
    }

    var currency;
    if( $('#currency').length ){
        currency = $('#currency').val();
    }else{
        currency = 'CZK';
    }

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( sUrl ) + '&doAction=validatebuynow',
        data: sData +'&condition='+condition+'&currency='+currency,
        success: function ( msg ) {

            if( msg != false ){
                $(document).ready(function(){
                    var message = showAuctionBidError( msg );
                    $("#example").html( message );

                    $("#example").dialog();
                    if( !$("#example").dialog( "isOpen" )  ){
                        $("#example").dialog( "open" );
                    }
                });

            }else{
                confirmBuyNow( cForm, sUrl, sRedirectURL );
            }

        }
    });

    return false;

}
	 
	 
/**
	  *  Funkce pro potvrzeni prihozu
	  */	  	 

function confirmAuctionBid( cForm, sUrl, sRedirectURL ) {
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );
		
    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();

    var buttonName1 = translate('Potvrdit');
    var buttonName2 = translate('Zrušit');

    var buttons = {};    
    buttons[buttonName1] = function() {
        addAuctionBid( cForm, '/auction/info/addBid', sRedirectURL );
    };
    buttons[buttonName2] = function() {
        $(this).dialog('close');
    }


    $.ajax({
        type: "POST",
        dataType: 'html',
        url: setURL( sUrl ),
        data: sData,
        success: function ( msg ) {
                    
            $("#confirmBidAJAX").html( msg );
                    
            $("#confirmBidAJAX").dialog({
                bgiframe: true,
                minHeight:200,
                modal: true,
                resize: true,
                width: 600,
                title: translate('Potvrzení Vašeho příhozu'),
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.5
                },
                buttons:buttons/* {
                    'Potvrdit': function() {
                        addAuctionBid( cForm, '/auction/info/addBid', sRedirectURL );
                    },
                    'Zrušit': function() {
                        $(this).dialog('close');
                    }
                }*/
            });
		            
            if( !$("#confirmBidAJAX").dialog( "isOpen" )  ){
                $("#confirmBidAJAX").dialog( "open" );
            }

        }
    });

    return false;
}

function confirmBuyNow( cForm, sUrl, sRedirectURL ) {
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();

    var condition;
    if( $('#condition').length ){
        if( $('#condition').is(':checked') ){
            condition = 1;
        }else{
            condition = 0;
        }
    }else{
        condition = 0;
    }

    var currency;
    if( $('#currency').length ){
        currency = $('#currency').val();
    }else{
        currency = 'CZK';
    }

    $.ajax({
        type: "POST",
        dataType: 'html',
        url: setURL( sUrl ),
        data: sData +'&condition='+condition+'&currency='+currency,
        success: function ( msg ) {

            $("#confirmBidAJAX").html( msg );

            var buttonName1 = translate('Potvrdit');
            var buttonName2 = translate('Zrušit');

            var buttons = {};
            buttons[buttonName1] = function() {
                endBuyNow( cForm, '/auction/info/buynow', sRedirectURL );
            };
            buttons[buttonName2] = function() {
                $(this).dialog('close');
            }

            $("#confirmBidAJAX").dialog({
                bgiframe: true,
                minHeight:200,
                modal: true,
                resize: true,
                width: 600,
                title: translate('Potvrzení akce Kup teď'),
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.5
                },
                buttons:buttons/* {
                    'Potvrdit': function() {
                        endBuyNow( cForm, '/auction/info/buynow', sRedirectURL );
                    },
                    'Zrušit': function() {
                        $(this).dialog('close');
                    }
                }*/
            });

            if( !$("#confirmBidAJAX").dialog( "isOpen" )  ){
                $("#confirmBidAJAX").dialog( "open" );
            }

        }
    });

    return false;
}
	 
	 
/**
     *  Funkce pro odeslani formulare pro pridani prihozu
     */	     
     
function addAuctionBid( cForm, sUrl, sRedirectURL ){
        
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );
		
    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( sUrl ),
        data: sData,
        success: function ( msg ) {

            if ( msg == "true" ) {
                redirectURL( sRedirectURL );
            } else {
                $("#confirmBidAJAX").dialog('destroy');
                validateAuctionBid( cForm, sUrl, sRedirectURL )
            }

        }
    });

    return false;
		
}

function endBuyNow( cForm, sUrl, sRedirectURL ){

    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();

    var currency;
    if( $('#currency').length ){
        currency = $('#currency').val();
    }else{
        currency = 'CZK';
    }

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( sUrl ),
        data: sData + '&currency='+currency+"&sDoAjax=true",
        success: function () {            
            redirectURL( sRedirectURL );
        }
    });

    return false;

}


/**
     *  Funkce pro odeslani formulare
     */

function sendForm( sData, sProcessURL, sRedirectURL ) {
    
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

    var cValidate = $.ajax({
        type: "POST",
        url: setURL( sProcessURL ),
        data: sData,
        success: function ( msg ) {

            showContent( sRedirectURL, 'level3' );
        //redirectURL( sRedirectURL );

        }
    });

}



/**
     *  Funkce pro odeslani formulare
     */

function searchForm( cForm, sProcessURL ) {

    cFormID   = $(cForm).attr('id');
    cF        = $( '#' + cFormID );
    sData     = cF.formSerialize();
    sURL      = sProcessURL + '?' + sData

    showContent( sURL, 'level3' );

}



/**
     *  Funkce pro zobrazeni chybovyche hlasek
     */

function showFormError( aError ) {

    var sErrorHTML = '<ul>';
    $( aError ).each( function ( iMsgID ) {

        sMsg = aError[ iMsgID ];
        sMsg = sMsg.split( '|' );
        sErrorHTML += '<li>' + sMsg[1] + '</li>';

        selectInputError( sMsg[0], true );

    });
    sErrorHTML += '</ul>';

    errorBox( true );
    handleContentData( sErrorHTML, sBoxError );

}
    
    
/**
     *  Funkce pro zobrazeni chybovyche hlasek
     */

function showAuctionBidError( aError ) {

    var sErrorHTML = '';
    $( aError ).each( function ( iMsgID ) {

        sMsg = aError[ iMsgID ];
        sMsg = sMsg.split( '|' );
        sErrorHTML += sMsg[1] + '<br />';

        selectInputError( sMsg[0], true );

    });
        
    return sErrorHTML;

}



/**
     *  Funkce pro skryti / zobrazeni boxu s chybovymi hlaskami
     */

function errorBox( bShow ) {

    if ( bShow == false )
        $('#bFormError').css({
            'display' : 'none'
        });
    else
        $('#bFormError').css({
            'display' : 'block'
        });

}



/**
     *  Funkce pro zruseni zvyrazneni u poli, ktera byly spatne vyplnena
     */

function clearFormErrors( aItems ) {

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

        selectInputError( aItems[i]['name'], false );

    }

    errorBox( false );

}


/**
     *  Funkce pro oznaceni chybne vyplnene casti formulare
     */

function selectInputError( sInput, bShow ) {

//if ( bShow == false )
//$( '#' + sInput ).css({ 'background-color' : '#f6f6f6' });
//else
//$( '#' + sInput ).css({ 'background-color' : '#ffff00' });


}



/**
     *  Funkce pro zatrzeni / odtrzeni vsech nastaveni v ramci jedne skupiny prav
     */

function checkAll( sID, sGroupID ) {

    aAction    = new Array
    aAction[0] = 'read';
    aAction[1] = 'write';
    aAction[2] = 'delete';

    if( $( '#' + sID + ':checked ' ).length ) {
        for ( i = 0; i < aAction.length; i++ ) {
            $( '#' + sGroupID + '__' + aAction[i] ).attr( "disabled", true );
            $( '#' + sGroupID + '__' + aAction[i] ).attr( "checked", false );
        }
    } else {
        for ( i = 0; i < aAction.length; i++ ) {
            $( '#' + sGroupID + '__' + aAction[i] ).attr( "disabled", false );
        }
    }

}



/**
     *  Funkce pro vyber typu subjektu
     */

function subjectType( sID )
{

    var sSelect = $('#'+sID).val();

    sCompany = ( sSelect == 'COMPANY' ) ? 'block' : 'none';
    sPerson  = ( sSelect == 'PERSON' )  ? 'block' : 'none';

    $('#d_company').css({
        'display':sCompany
    });
    $('#d_person').css({
        'display':sPerson
    });

}



/**
     *  Funkce pro vyber typu subjektu
     */

function userType( sID )
{

    var sSelect = $('#'+sID).val();

    sPerson = ( sSelect == 'PERSON' ) ? 'block' : 'none';
    sRoom   = ( sSelect == 'ROOM' )  ? 'block' : 'none';

    $('#d_person').css({
        'display':sPerson
    });
    $('#d_room').css({
        'display':sRoom
    });

}



/**
     *  Funkce pro vyber adresy
     */

function  showAddress( sID )
{

    var sSelect = $('#'+sID).val();

    if ( sSelect != '' ) {
        sCzech   = ( sSelect == '1' )  ? 'block' : 'none';
        sForeign = ( sSelect != '1' )  ? 'block' : 'none';
    } else {
        sCzech   = 'none';
        sForeign = 'none';
    }

    $('#d_uiradr').css({
        'display':sCzech
    });
    $('#d_address').css({
        'display':sForeign
    });

}



/**
     *  Funkce pro zobrazeni nastaveni adresy
     */

function  showAddressSettings( sID )
{

    var sSelect = $('#'+sID).val();
    sShow = ( sSelect == '' )  ? 'block' : 'none';

    $('#d_address_settings').css({
        'display':sShow
    });

}



/**
     *  Funkce pro formulare aktivaci zadavaci casti formulare
     */

function  doActive( sID )
{

    var sSelect = $('#'+sID+':checked');
    sShow = ( sSelect.length )  ? 'block' : 'none';

    $('#d_active').css({
        'display':sShow
    });

}



/**
     *  Funkce pro zpracovani formulare pro hlasovou schranku
     */

function voiceMessage( sID, sPart) {

    var sSelect = $('#'+sID+':checked');

    if ( sPart == 'default' ) {
        if ( $('#default-0:checked').length ) {
            $('#d_file').css({
                'display':'block'
            });
            $('#d_locale').css({
                'display':'none'
            });
        }
        if ( $('#default-1:checked').length ) {
            $('#d_file').css({
                'display':'none'
            });
            $('#d_locale').css({
                'display':'block'
            });
        }
    }

    if ( sPart == 'sms' ) {
        if ( $('#sms:checked').length ) {
            $('#d_sms_number').css({
                'display':'block'
            });
        } else {
            $('#d_sms_number').css({
                'display':'none'
            });
        }
    }

}



/**
     *  Funkce pro zpracovani formulare pro presmerovani
     */

function redirect( sID, sPart) {

    var sSelect = $('#'+sID+':checked');

    if ( sPart == 'call_type' ) {
        $('#target-VOICE').attr({
            'disabled':true
        });
        $('#target-FAX').attr({
            'disabled':true
        });
        $('#target-ALL').attr({
            'checked':true
        });
        $('#target-PHONE').attr({
            'checked':true
        });
    }

    if ( sPart == 'call_type' || sPart == 'target' ) {
        $('#d_phone_number').css({
            'display':'none'
        });
        $('#d_voice_messages_id').css({
            'display':'none'
        });
        $('#d_fax2mail_id').css({
            'display':'none'
        });
        $('#d_phone').css({
            'display':'none'
        });
    }

    if ( sPart == 'call_type' ) {

        if ( $('#call_type-ALL:checked').length ) {
            $('#target-VOICE').attr({
                'disabled':false
            });
            $('#target-FAX').attr({
                'disabled':false
            });
            $('#d_phone_number').css({
                'display':'block'
            });
            $('#d_phone').css({
                'display':'block'
            });
        }

        if ( $('#call_type-VOICE:checked').length ) {
            $('#target-VOICE').attr({
                'disabled':false
            });
            $('#d_phone_number').css({
                'display':'block'
            });
            $('#d_phone').css({
                'display':'block'
            });
        }

        if ( $('#call_type-FAX:checked').length ) {
            $('#target-FAX').attr({
                'disabled':false
            });
            $('#target-FAX').attr({
                'checked':true
            });
            $('#d_fax2mail_id').css({
                'display':'block'
            });
        }
    }

    if ( sPart == 'target' ) {

        if ( $('#target-PHONE:checked').length ) {
            $('#d_phone_number').css({
                'display':'block'
            });
            $('#d_phone').css({
                'display':'block'
            });
        }

        if ( $('#target-VOICE:checked').length ) {
            $('#d_voice_messages_id').css({
                'display':'block'
            });
        }

        if ( $('#target-FAX:checked').length ) {
            $('#d_fax2mail_id').css({
                'display':'block'
            });
        }

    }

}



/**
     *  Funkce pro zpracovani akce a pripadne vraceni vygenerovaneho textu do obsahu volaneho prvku
     */

function processAction( sUrl, sItem, cProcess ) {
    
    $.cookie( 'sUrl', sUrl );
    $.cookie( 'sPartID', setPartID( sUrl ) );
    $.cookie( 'sBaseUrl', setBaseUrl( sUrl ) );

    sSeparator = ( sUrl.indexOf('?') > 0 ) ? '&' : '?';

    $.ajax({
        url: sUrl + sSeparator + 'doAjax=true',
        success: function ( msg ) {
            if ( cProcess == true ) {
                $(sItem).text( msg );
            }
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
        }
    });

    return false;

}


/**
     *  Funkce pro pridani textoveho elementu
     */

function addTextElement( currentItem, newItem ) {

    aItems = $("input[@id*='" + newItem + "']");
    sLastItem = aItems[ aItems.length - 1 ].id;

    aID = sLastItem.split( '_' );

    if ( ( aID.length == 1 ) || ( aID.length == 2 && isNaN( parseInt( aID[1] ) ) ) ) {
        itemNumber = 1;
    } else {
        itemNumber = ( aID.length == 2 ) ? parseInt( aID[1] ) + 1 : parseInt( aID[2] ) + 1;
    }

    var itemElement = '<div id="d_' + newItem + '_' + itemNumber + '" class="fItemInner"><input type="text" id="' + newItem + '_' + itemNumber + '"name="' + newItem + '_' + itemNumber + '" value="" size="30" class="fItem_text" onchange="deleteElement(this);" />';

    elementId = ( itemNumber == 1 ) ? newItem : 'd_' + newItem + '_' + ( itemNumber - 1 );

    $('#'+elementId).after( itemElement );

}



/**
     *  Funkce pro pridani textovych elementu
     */

function addTextElements( currentItem, newItem, styleItem ) {

    aItems = $("input[@id*='" + newItem[0] + "']");
    sLastItem = aItems[ aItems.length - 1 ].id;

    aID = sLastItem.split( '_' );

    if ( ( aID.length == 1 ) || ( aID.length == 2 && isNaN( parseInt( aID[1] ) ) ) ) {
        itemNumber = 1;
    } else {
        itemNumber = ( aID.length == 2 ) ? parseInt( aID[1] ) + 1 : parseInt( aID[2] ) + 1;
    }

         
    var itemElement = '<div id="d_' + newItem[0] + '_' + itemNumber + '" class="fItemInner">';
        
    for ( var i in newItem )
    {
        itemElement += '<input type="text" id="' + newItem[i] + '_' + itemNumber + '"name="' + newItem[i] + '_' + itemNumber + '" value="" size="30" class="fItem_text' + ( styleItem ? styleItem : '' ) + '" onchange="deleteElement(this);" />';
    }

    itemElement += '</div>';
        
    elementId = ( itemNumber == 1 ) ? newItem[1] : 'd_' + newItem[0] + '_' + ( itemNumber - 1 );

    $('#'+elementId).after( itemElement );

}
    


/**
     *  Funkce pro pridani textoveho elementu
     */

function deleteElement( cItem ) {

    cItem = $(cItem);

    if ( cItem.val() == '' ) {
        $('#d_'+cItem.attr('id')).remove();
    }

}



/**
     *  Funkce pro vygenerovani nahodneho cisla
     */

function getRandom() {

    return Math.round( 1000000000000 * Math.random() );

}



/**
     *  Funkce pro generovani URL pro odeslani AJAXu
     */

function setURL( sUrl ) {

    sSeparator = ( sUrl.indexOf('?') > 0 ) ? '&' : '?';
    return sUrl + sSeparator + 'doAjax=true&_i=' + getRandom();

}



/**
     *  Vypnuti klasevy Enter ve formulari
     */

/*    $(document).ready(function() {
        $("#UpdateForm").bind( "keypress", function( e ) {
            sKeyCode = ( e.keyCode && e.keyCode > 0 ) ? e.keyCode : e.which;
            if ( sKeyCode == 13 ) {
                return false;
            }
        });
    });*/


function showSearch() {
    $('#pSearch').slideToggle('slow');
}
    
    
/**
     *  Prepnuti na skryte pole formulare pomoci onclick v inputu typu checkbox
     */	    
	 
function showLanguageValues( idSwitcher, idHide, idShow ){
    var switcher = document.getElementById(idSwitcher);
    var hide = document.getElementById(idHide);
    var show = document.getElementById(idShow);
	    
    if( switcher.checked == true ){
        hide.style.display = 'none';
        show.style.display = 'block';
	       
        deleteInput( hide, 'text' );
    }else{
        hide.style.display = 'block';
        show.style.display = 'none';
	       
        deleteInput( show, 'text' );
    }
}
	 
	 
/**
	  *  Funkce pro vynulovani input poli
	  */	  	  
	  
function deleteInput( element, type ){
    var inputArray = element.getElementsByTagName( 'input' );
    for( var i = 0; i < inputArray.length; i++ ){
        if( inputArray[i].type == type ){
            inputArray[i].value = '';
        }
    }
}




function doLogin() {

    showLoginLoader();

    cF        = $( '#loginForm' );
    sUrl      = '/login';
    sData     = cF.formSerialize();
    //sBoxError = "bFormError";

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( sUrl ),
        data: sData,
        success: function ( msg ) {

            if ( msg == 'false' ) {
                $('#sBoxError').text('Nepodařilo se přihlásit');
            } else if ( msg == 'true' ) {
                redirectURL( '/' );
            }

            hideLoginLoader();

        }
    });

    return false;

}


function showLoginLoader() {
    $('#pLoginLoader').fadeIn('fast');
}

function hideLoginLoader() {
    setTimeout( function() {
        $('#pLoginLoader').fadeOut('fast');
    }, 500 );
}


function setURL( sUrl ) {

    sSeparator = ( sUrl.indexOf('?') > 0 ) ? '&' : '?';
    return sUrl + sSeparator + 'doAjax=true&_i=' + getRandom();

}


function getRandom() {

    return Math.round( 1000000000000 * Math.random() );

}



function checkAuction( auctionID, itemID ) {

    sUrl = '/auction-info/' + auctionID + '/currentStatus/itemID/' + itemID;

    $.ajax({
        type: "GET",
        dataType: 'json',
        url: setURL( sUrl ),
        success: function ( data ) {

            $('.currentPrice').html( data['current'] );
            $('.currentPriceEur').html( data['currentEur'] );
            $('.currentPriceEur2').html( data['currentEur2'] );
            $('.minBid').html( data['minimal'] );
            $('.minBidEur').html( data['minimalEur'] );
            $('.minBidEur2').html( data['minimalEur2'] );
            $('.closeDate').html( data['close'] );

            if( data['isRunning'] == false ){
                $('.pBid').css('display','none');
            }

            setTimeout( function() {
                checkAuction( auctionID, itemID );
            }, 10000 );

        },
        error: function ( error ) {

            console.error ( 'Error: ', error );

            setTimeout( function() {
                checkAuction( auctionID, itemID );
            }, 10000 );

        }
    });

}



function selectItem( cItem ) {

    sID      = $(cItem).attr('value');
    cChecked = $(cItem+':checked');
    /*if ( cChecked.length ) {
            sValue = 1;
        } else {
            sValue = 0;
        }*/
        
    if( cItem.checked ){
        sValue = 1;
    }else{
        sValue = 0;
    }

    sUrl = '/auction/user/select/itemID/' + sID + '/value/' + sValue;

    $.ajax({
        type: "GET",
        dataType: 'json',
        url: setURL( sUrl ),
        success: function ( data ) {
        //alert( data );
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
        }
    });

}
    
    
	
function sendUserAjax( iID, iFrom, iTotal, iBreak, iLimitTotal, iLimitTo ){

    sUrl = '/backoffice/sendMailing/senduserajax/id/' + iID + '/from/' + iFrom + '/total/' + iTotal + '/break/' + iBreak + '/limitTotal/' + iLimitTotal + '/limitTo/' + iLimitTo;

    $.ajax({
        type: "GET",
        dataType: 'json',
        url: setURL( sUrl ),
        success: function ( data ) {
            if( data['info'] == '' ){
                setTimeout( function(){
                    sendUserAjax( iID, data['from'], data['total'], data['break'], data['limitTotal'] , data['limitTo'] );
                }, 10000 );
            }else{
                setTimeout( function(){
                    sendMailingAjax( iID, 0, 0, 0, 0, 0 );
                }, 10000 );
						
            }
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
        }
    });
	
}
	
	
function sendMailingAjax( iID, iFrom, iTotal, iBreak, iLimitTotal, iLimitTo ){

    sUrl = '/backoffice/sendMailing/sendmailingajax/id/' + iID + '/from/' + iFrom + '/total/' + iTotal + '/break/' + iBreak + '/limitTotal/' + iLimitTotal + '/limitTo/' + iLimitTo;

    $.ajax({
        type: "GET",
        dataType: 'json',
        url: setURL( sUrl ),
        success: function ( data ) {
            if( data['info'] == '' ){
                setTimeout( function(){
                    sendMailingAjax( iID, data['from'], data['total'], data['break'], data['limitTotal'] , data['limitTo'] );
                }, 10000 );
            }else{
                alert( 'Odesílání e-mailů bylo úspěšně ukončeno' );
            }
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
        }
    });
	
}

    
	
function unSelectItem( cItem ) {

    selectItem( cItem );
    $(cItem).parent().parent().remove();

}



function getFormAction( cItem ) {
    var sAction = $( cItem ).val();
    showLoaderBox();
    $.ajax({
        type: "POST",
        dataType: 'html',
        url: setURL( '/registration/getForm' ),
        data: 'cuDesicion=' + sAction + '',
        success: function ( sData ) {
            $('#regForm').html( sData );
            hideLoaderBox();
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
            hideLoaderBox();
        }
    });
}


function showLoaderBox() {
    var sPic = '<img src="/public/images/ajax-loader.gif" />';
    var sBody = '' + sPic + '';
    $.blockUI({
        message: '' + sBody + '',
        css: {
            'border':'1px solid red',
            'padding':'10px'
        },
        /*overlayCSS:  {
                'background-color':'gray', 
                'opacity':'0.6'
            },*/
        baseZ: 9999,
        showOverlay: true
    });
}

function hideLoaderBox() {
    $.unblockUI();
}



function addAuctionFund( iUserID ) {
    showLoaderBox();
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( '/backoffice/user/getAjaxFundForm' ),
        success: function ( aData ) {
                
            $('#dialog').bind( 'dilogclose', function() {
                $('#dialog').dialog('destroy');
            } );

            $('#dialog').text('');
            $('#dialog').html('');

            var aAuction = new Array;
            for( var i in aData ) {
                aAuction[i] = aData[i];
            }

            $('#dialog').createAppend(
                'div', {
                    className: 'pForm',
                    id: 'pForm'
                }
                );

            $('#pForm').createAppend(
                'div', {
                    id: 'isFund'
                }, ''
                );

            $('#pForm').createAppend(
                'div', {
                    className:'fItem dialogItem'
                }, [
                'label', {
                    style: 'width: 150px; margin: 0px;'
                }, 'Aukce',
                'select', {
                    id:'auction_item',
                    name: 'auction_item',
                    onchange: 'isFund(this)'
                }, ''
                ]
                );

            $('#auction_item').addOption( aAuction, false );

            $('#pForm').createAppend(
                'div', {
                    className:'fItem dialogItem'
                }, [
                'label', {
                    style: 'width: 150px; margin: 0px;'
                }, 'Jistina( částka )',
                'input', {
                    type: 'text',
                    id:'fund_amount',
                    name: 'fund_amount',
                    className: 'fItem_text'
                }
                ]
                );
                
                
            $('#dialog').dialog({
                modal: true,
                resize: false,
                width: 750,
                title: 'Zadání jistiny',
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.5
                },
                buttons: {
                    'OK': function() {
                        checkAddAuctionFund( iUserID );
                    },
                    'Zrušit': function() {
                        $('#dialog').dialog('destroy');
                    }
                }
            });
                
            hideLoaderBox();
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
            hideLoaderBox();
        }
    });
}



function isFund( cItem ) {
    var iID = $(cItem).val();
        
    if( iID != '' ) {
        showLoaderBox();
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: setURL( '/backoffice/user/getAjaxFundAuction' ),
            data: 'iID=' + iID + '',
            success: function ( iData ) {
                if( iData == 0 ) {
                    $('#isFund').html( '<a href="javascript:void(0)" onclick="saveAuctionFund(' + iID + ')" style="color: red;">Není aukce s jistinou - nastavit</a>' );
                } else {
                    $('#isFund').html( '' );
                }
                hideLoaderBox();
            },
            error: function ( error ) {
                console.error ( 'Error: ', error );
                hideLoaderBox();
            }
        });
    } else {
        $('#isFund').html( '' );
    }
}



function checkAddAuctionFund( iUserID ) {
    var result = '';
    var iID = $('#auction_item').val();
    if( iID == '' ) {
        iID = 0;
    }
        
    showLoaderBox();
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( '/backoffice/user/getAjaxFundAuction' ),
        data: 'iID=' + iID + '',
        success: function ( iData ) {
            if( iData == 0 ) {
                var isF = 0;
            } else {
                var isF = 1;
            }
            hideLoaderBox();

            if( isF == 0 ) {
                result = String( result ) + 'Aukce musí být s jistinou. Prosím nastavte na danou aukci jistinu.<br />';
            }
            if( $('#fund_amount').val() == '' ) {
                result = String( result ) + 'Musíte vyplnit částku, kterou zákazník zaplatil.<br />';
            }
        
            if( result != '' ) {
                result = '<div style="text-align: left">' + String( result ) + '</div>';
                $('#dialogErr').html( result );
                $('#dialogErr').dialog({
                    modal: true,
                    resize: false,
                    width: 600,
                    title: 'Chyby',
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.5
                    },
                    buttons: {
                        'OK': function() {
                            $('#dialogErr').dialog('destroy');
                        }
                    }
                });
            } else {
                saveUserFund( iUserID );
            }
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
            hideLoaderBox();
        }
    });
}


function saveAuctionFund( iAuctionID ) {
    showLoaderBox();
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( '/backoffice/user/saveAjaxFundAuction' ),
        data: 'iID=' + iAuctionID + '',
        success: function ( iData ) {
            if( iData == 1 ) {
                $('#isFund').html( '' );
            } else {
                alert( 'Nepodařilo se uložit. Opakujte akci později.' );
            }

            hideLoaderBox();
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
            hideLoaderBox();
        }
    });
}


function saveUserFund( iUserID ) {        
    showLoaderBox();
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: setURL( '/backoffice/user/saveUserFund' ),
        data: 'iUserID=' + iUserID + '&iAuctionID=' + $('#auction_item').val() + '&iAmount=' + $('#fund_amount').val() + '',
        success: function ( iData ) {
            if( iData == 0 ) {
                alert( 'Nepodařilo se uložit. Opakujte akci později.' );
            }
            hideLoaderBox();
            $('#dialog').dialog('destroy');
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
            hideLoaderBox();
        }
    });
}


function startCycling() {        
    $.ajax({
        type: "POST",
        dataType: 'html',
        url: setURL( '/auth/user' ),
        success: function ( sData ) {
            $('#obsah-box').html( sData );
            setTimeout( function() {
                startCycling();
            }, 10000 );
        },
        error: function ( error ) {
            console.error ( 'Error: ', error );
        }
    });
}

function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}




/**
     * Nacteni skriptu po nacteni stranky
     */


$(document).ready(function(){

    /*$('.popeye').popeye({
            direction:  'right',
            duration:   230,
            stageW:     '175px',
            stageH:     '175px',
            nlabel:     'další',
            plabel:     'předchozí',
            oflabel:    'z',
            blabel:     'zvětšit',
            clabel:     'Klikněte pro zavření'
        });*/

    $('.jGallery').jcarousel({
        scroll: 1,
        auto: 5,
        wrap: 'last',
        initCallback: mycarousel_initCallback
    });

    $('a.lightBox').lightBox({
        fixedNavigation:true
    });

    $('#hodiny').jclock();

    if( $.url.attr('path') == '/auth/user' ) {
        setTimeout( function() {
            startCycling();
        }, 10000 );
    }

});

