
String.prototype.nativeSplit = String.prototype.split;
String.prototype.split = function( d ) {
    var ar = this.nativeSplit( d );
    return ar.length == 1 && ar[0] == '' ? [] : ar;
}

function submitForm( fieldNames, fieldValues, formId )
{
    var arFieldNames = fieldNames.split(',');
    var arFieldValues = fieldValues.split(',');
    var jParentForm;

    for ( var i in arFieldNames )
        $( '#' + arFieldNames[i] ).val( arFieldValues[i] );

    if ( formId )
        jParentForm = $( '#' + formId );

    if ( !jParentForm || jParentForm.length == 0 )
        jParentForm = $( '#' + arFieldNames[i] ).parents( 'form' );

    return jParentForm.length ? jParentForm.submit() && false : true;
}

function submitFormPopup( formId, url, target )
{
    var f = document.getElementById( formId );
    var t = f.target;
    var a = f.action;
    if( typeof( target ) == 'undefined' )
        target = '_blank';
    f.target = target;
    if ( url )
        f.action = url;
    f.submit();
    f.target = t;
    f.action = a;
    return false;
}

function toggleSection(sGroupName, arGroupNames, openedCaption, closedCaption )
{
    if ( $( '#tab_' + sGroupName ).hasClass( 'activeTab' ) )
    {
        $( '#' + sGroupName ).val( '' );
        $( '#cmd_' + sGroupName ).text( closedCaption );
    }
    else
    {

        for ( var i = 0; i != arGroupNames.length; i++ )
            if ( $( '#tab_' + arGroupNames[i] ).hasClass( 'activeTab' ) )
                $( '#cmd_' + arGroupNames[i] ).click();

        $( '#' +sGroupName ).val('1');
        $( '#cmd_' + sGroupName ).text( openedCaption );
    }

    $( '#group_' + sGroupName ).toggle();
    $( '#tab_' + sGroupName ).toggleClass( 'activeTab' );

    return false;
}

function toggleListCheckboxes( listName ){
    if ( document.getElementById( listName + '_selRows' ).value != '' ){
        var arControlNames = document.getElementById( listName + '_selRows' ).value.split(',');
        for ( var i = 0; i != arControlNames.length; i++ ){
            document.getElementById( listName + '_' + arControlNames[i] ).checked = document.getElementById( listName + '_selall' ).checked;
        }
    }
}

function toggleListCheckboxes( listName ){

    var s = $( '#' + listName + '_selRows' ).val().replace( /\d+/g, ',#' + listName + '_' + '$&' );
    $( '#' + listName + '_selall' ).attr( 'checked' ) ? $( s ).attr( 'checked', 'checked' ) : $( s ).removeAttr( 'checked' );
}

function getFlashMovieObject( movieName )
{
    if (window.document[movieName])
    {
        return window.document[movieName];
    }
    if (navigator.appName.indexOf("Microsoft Internet")==-1)
    {
        if (document.embeds && document.embeds[movieName])
            return document.embeds[movieName];
    }
    else
    {
        return document.getElementById(movieName);
    }
}

function getEventSrcElement( e ) {
    if (!e) e = window.event;
    if ( e.srcElement )
        return e.srcElement;
    else
        return e.target;
}

/*function openCalendarWindow( e, dateTimeControlId, ShowYearSelect, ShowMonthSelect, ShowOneYearStep, ShowOneMonthStep, DateFormat )
{
    var url = 'calendar.aspx?showyearselect=' + ShowYearSelect +
                '&showmonthselect=' + ShowMonthSelect +
                '&showoneyearstep=' + ShowOneYearStep +
                '&showonemonthstep=' + ShowOneMonthStep +
                '&controlid=' + dateTimeControlId +
                '&controlvalue=' + document.getElementById( dateTimeControlId ).value +
                '&DateFormat=' + DateFormat;

    e = $.event.fix( e );

    if( ( typeof showCalendarPopup == "function" ) )
    {
        showCalendarPopup( e, url, 200, 250 )
    }
    else
    {
        var calendar = window.open( url, 'calendar', 'height=250, width=200, left=' + e.screenX + ', top=' + e.screenY );
        calendar.focus();
    }
    return calendar;
}*/

function fillOpenerControls( controlIds, values, bSubmitParentForm ){

    var parentDoc = parent.document;
    if ( window.opener )
        parentDoc = window.opener.document;

    for ( var i in controlIds )
        $( '#' + controlIds[i], parentDoc ).val( values[i] );

    if ( bSubmitParentForm )
        $( '#' + controlIds[i], parentDoc ).parents( 'form' ).submit();

    if ( window.opener )
    {
        window.opener.focus();
        window.close();
    }
}


function fillOpenerControl( controlId, value, bSubmitParentForm ){
    fillOpenerControls( [ controlId ], [ value ], bSubmitParentForm );
}


function fillOpenerLinkObjectControl( controlId, valueId, valueName ){

    if ( window.opener.linkObjectControlOnValueSet != undefined )
        window.opener.linkObjectControlOnValueSet( controlId, valueId, valueName );

    fillOpenerControls(
        [ controlId, controlId + 'Name' ],
        [ valueId, valueName ],
        false
    )
    return false;
}

function addArrayPropItems( sResFieldId, sUrl, sWindowMode ){
    return $( '#' + sResFieldId ).val() ? true : window.open( sUrl, "" , sWindowMode ) && false;
}

function removeArrayPropItem( arrPropEditorName, arrPropEditorGroupName ){

    $( '#' + arrPropEditorGroupName + 'remove' ).attr( 'checked', 'checked' );
    $( '#' + arrPropEditorName + '_remove' ).click();
}

function arrayPropEditorSyncronizeControls()
{
    var editorName = $( '#editor-name' ).val();

    var elementIds = '';
    for( i = 0; i < document.forms[ 0 ].elements.length; i++ )
        elementIds += '#' + document.forms[0].elements[i].id + ',';

    if ( $( '#first-display' )[0] )
    {
        $( elementIds ).each(
            function(){
                var elem = this;
                var parentElem = $( '#' + editorName + elem.id, window.opener.document )[0];

                if ( parentElem )
                    if( parentElem.type == 'checkbox' )
                        if( elem.type == 'checkbox' )
                            elem.checked = parentElem.checked;
                        else
                            elem.value = parentElem.checked ? parentElem.value : '';
                    else
                        if( elem.type == 'checkbox' )
                            elem.checked = parentElem.value ? true : false;
                        else
                            elem.value = parentElem.value;
            }
        );
    }

    if ( document.getElementById( "success" ) != null )
    {
        $( elementIds ).each(
            function(){
            var elem = this;
            var parentElem = $( '#' + editorName + elem.id, window.opener.document )[0];

            if ( parentElem )
                if( elem.type == 'checkbox' )
                    if( parentElem.type == 'checkbox' )
                        parentElem.checked = elem.checked;
                    else
                        parentElem.value = elem.checked ? elem.value : '';
                else
                    if( parentElem.type == 'checkbox' )
                        parentElem.checked = elem.value ? true : false;
                    else
                        parentElem.value = elem.value;
            }
        );

        var propEditorName = $( '#array-prop-editor-name' ).val();
        if ( propEditorName )
        {
            $( '#' + propEditorName, window.opener.document ).val( 1 );
            $( '#' + propEditorName + '_add', window.opener.document ).click();
        }
        window.close();
    }
}

function getListSelectedItems( sListName )
{
    var checkedRowsIds = $( '#' + sListName + '_checkedRows' ).val();
    var arSelectableRowsIds = $( '#' + sListName + '_selRows' ).val().split( ',' );

    for( var i in arSelectableRowsIds )
    {
        var checkbox = $( '#' + sListName + '_' + arSelectableRowsIds[i] )[0];
        if ( checkbox.checked  )
        {
            var reg = new RegExp (
                '(^' + arSelectableRowsIds[i] + ',)|' +
                '(^' + arSelectableRowsIds[i] + '$)|' +
                '(,' + arSelectableRowsIds[i] + ',)|' +
                '(,' + arSelectableRowsIds[i] + '$)' );
            if( checkedRowsIds.match( reg ) == null )
                checkedRowsIds += ( checkedRowsIds.length > 0 ? ',' : '' ) + arSelectableRowsIds[i];
        }

        if ( !checkbox.checked )
        {
            var reg = new RegExp (
                '^' + arSelectableRowsIds[i] + ',|' +
                '^' + arSelectableRowsIds[i] + '$|' +
                ',' + arSelectableRowsIds[i] + '(,)|' +
                ',' + arSelectableRowsIds[i] + '$' );
            checkedRowsIds = checkedRowsIds.replace( reg, '$1' );
        }
    }
    return checkedRowsIds;
}

function getTreeSelectedItems( sTreeName )
{
    var arSelectedNodeIds = new Array();

    $( 'input[id^=' + sTreeName + '_checkbox_]:checked' ).each(
        function(){ arSelectedNodeIds.push( this.id.replace( sTreeName + '_checkbox_', '' ) ) }
    );
    return arSelectedNodeIds.join( ',' );
}

function returnArrayPropSelectedItems( sSelectorName, sOpenerControlId, sSelectorType )
{
    var sRes = '';

    if ( !sSelectorType ) sSelectorType = 'list';

    if ( sSelectorType == 'list' )
        sRes = getListSelectedItems( sSelectorName );
    else if ( sSelectorType == 'tree')
        sRes = getTreeSelectedItems( sSelectorName );

    try
    {
        returnArrayPropValue( sRes, sOpenerControlId );
        window.close();
    }
    catch( e ){}
}

function returnArrayPropValue( nValue, sOpenerControlId )
{
    var controlToReturn = $( '#' + sOpenerControlId, window.opener.document );
    controlToReturn.val( nValue );
    window.opener.focus();
    $( '#' + sOpenerControlId + '_add', window.opener.document ).click();
}

function moveArrayPropertyEditorItemUp( id, down )
{
    var idPrev = $( '#' + id ).prev( 'tr[@id]' ).attr( 'id' );
    if ( idPrev )
    {
        $( '#' + ( down ? idPrev : id ) ).addClass( 'active' );

        var hasActiveState = $( '#' + ( down ? idPrev : id ) ).css( 'backgroundColor' ) != $( '#' + ( down ? id : idPrev ) );
        if( !hasActiveState )
            $( '#' + ( down ? idPrev : id ) ).removeClass( 'active' );

        var checkboxCache = [];
        if ( $.browser.msie )
            $( '#' + id + ' input:checkbox:checked' ).each(
                function( i ){
                    checkboxCache[ i ] = '#' + this.id;
                }
            );

        if ( hasActiveState )
            setTimeout( function(){ $( '#' + idPrev ).before( $( '#' + id ) ) }, 20 );
        else
            $( '#' + idPrev ).before( $( '#' + id ) );

        var curOldOrder = $( '#' + id + '_order' ).val();
        $( '#' + id + '_order' ).val( $( '#' + idPrev + '_order' ).val() );
        $( '#' + idPrev + '_order' ).val( curOldOrder );

        if ( $.browser.msie )
            $( checkboxCache.join( ',' ) ).attr( 'checked', 'checked' );

        if( hasActiveState )
        {
            var defaultBgColor = $( '#' + ( down ? id : idPrev ) ).children( 'td' ).css( 'backgroundColor' );
            setTimeout ( function(){
                $( '#' + ( down ? idPrev : id ) + ' td' ).animate(
                    { backgroundColor: defaultBgColor },
                    500,
                    function(){
                        $( this )[0].style.backgroundColor = '';
                        $( this ).parent( 'tr' ).removeClass( 'active' );
                    }
                )
            }, 20 );
        }
    }
}

function moveArrayPropertyEditorItemDown( id )
{
    var nextId = $( '#' + id ).next( 'tr[id][class!=newItemEditorRow]' ).attr( 'id' );
    if ( nextId )
        moveArrayPropertyEditorItemUp( nextId, true );
}


function initClientMultiSelectControls()
{
    $( '.clientMultiSelectControl' ).each(
        function()
        {
            var containerLength = 0 - '_container'.length;
            var controlId = this.id.slice( 0, containerLength );
            var ids = ( $( "#" + controlId ).val() ).split( ',' );
            var values = ( $( "#" + controlId + "_values" ).val() ).split( ',,' );
            for ( var i in ids )
                addClientMultiSelectOption( controlId, ids[i], values[i], window.document );
        }
    );
}

$( initClientMultiSelectControls );

function addClientMultiSelectOption( controlId, id, value, document )
{
    value = value.replace( ',.', ',' );
    $( '#' + controlId + '_controls', document ).append(
        '<div id="' + controlId + id + '">' +
            value + ' ' +
            '<img src="img/remove.gif" title="remove" alt="Clear" class="imgclear" onclick="deleteClientMultiSelectOption( \'' +
            controlId + '\',\'' + id + '\' )"/>' +
        '</div>'
    );
}

function addClientMultiSelectOptionsFromList( listControlId, parentControlId )
{
    var checkedRowsIds = $( '#' + listControlId + '_checkedRows' ).val();
    var arSelectableRowsIds = $( '#' + listControlId + '_selRows' ).val().split( ',' );

    var checkedRowsValues = $( '#' + listControlId + '_checkedRows_values' ).val();

    for( var i in arSelectableRowsIds )
    {
        var checkbox = $( '#' + listControlId + '_' + arSelectableRowsIds[i] )[0];
        var selCheckboxValue = $( '#' + listControlId + '_' + arSelectableRowsIds[i] + '_text' ).val().replace( ',', ',.' )
        if ( checkbox.checked  )
        {
            var reg = new RegExp (
                '(^' + arSelectableRowsIds[i] + ',)|' +
                '(^' + arSelectableRowsIds[i] + '$)|' +
                '(,' + arSelectableRowsIds[i] + ',)|' +
                '(,' + arSelectableRowsIds[i] + '$)' );
            if( checkedRowsIds.match( reg ) == null )
            {
                checkedRowsIds += ( checkedRowsIds.length > 0 ? ',' : '' ) + arSelectableRowsIds[i];
                checkedRowsValues += ( checkedRowsValues.length > 0 ? ',,' : '' ) + selCheckboxValue;
            }
        }
        if ( !checkbox.checked )
        {
            var reg = new RegExp (
                '^' + arSelectableRowsIds[i] + ',|' +
                '^' + arSelectableRowsIds[i] + '$|' +
                ',' + arSelectableRowsIds[i] + '(,)|' +
                ',' + arSelectableRowsIds[i] + '$' );
            checkedRowsIds = checkedRowsIds.replace( reg, '$1' );
            var reg = new RegExp (
                '^' + selCheckboxValue + ',,|' +
                '^' + selCheckboxValue + '$|' +
                ',,' + selCheckboxValue + '(,,)|' +
                ',,' + selCheckboxValue + '$' );
            checkedRowsValues = checkedRowsValues.replace( reg, '$1' );
        }
    }

    var idArray = checkedRowsIds.split( ',' );
    var valueArray = checkedRowsValues.split( ',,' );
    var ids = $( '#' + parentControlId, window.opener.document ).val();
    var selectedIdArray = ids.split(',');
    var values = $( '#' + parentControlId + '_values', window.opener.document ).val();

    for ( var i in idArray )
    {
        var id = idArray[i];
        var value = valueArray[i];
        var isUnique = true;
        for ( var k in selectedIdArray )
        {
            if ( selectedIdArray[k] == id )
            {
                isUnique = false;
                break;
            }
        }
        if ( isUnique )
        {
            addClientMultiSelectOption( parentControlId, id, value.replace( ',.', ',' ), window.opener.document );

            ids += ( ids != '' ? ',' : '' ) + id;
            values += ( values != '' ? ',,' : '' ) + value;
        }
    }

    $( '#' + parentControlId, window.opener.document ).val( ids );
    $( '#' + parentControlId + '_values', window.opener.document ).val( values );

    window.close();
    return true;
}

function addClientMultiSelectOptionsFromTree( treeControlId, parentControlId )
{
    var idArray = getTreeSelectedItems( treeControlId ).split( ',' );
    var ids = $( '#' + parentControlId, window.opener.document ).val();
    var selectedIdArray = ids.split(',');
    var values = $( '#' + parentControlId + '_values', window.opener.document ).val();

    for ( var i in idArray )
    {
        var id = idArray[i];
        var value = $( '#' + treeControlId + '_' + id + ' > a' ).text();
        var isUnique = true;
        for ( var k in selectedIdArray )
        {
            if ( selectedIdArray[k] == id )
            {
                isUnique = false;
                break;
            }
        }
        if ( isUnique )
        {
            var hidValue = value.replace( ',', ',.' );

            addClientMultiSelectOption( parentControlId, id, value, window.opener.document );

            ids += ( ids != '' ? ',' : '' ) + id;
            values += ( values != '' ? ',,' : '' ) + hidValue;
        }
    }

    $( '#' + parentControlId, window.opener.document ).val( ids );
    $( '#' + parentControlId + '_values', window.opener.document ).val( values );

    window.close();
    return true;
}

function deleteClientMultiSelectOption( control, id )
{
    $( '#' + control + id ).remove();

    var ids = $( '#' + control ).val().split( ',' );
    var values = $( '#' + control + '_values' ).val().split( ",," );
    var newIds = '';
    var newValues = '';

    for( var i in ids )
    {
        if ( ids[i] != id )
        {
            newIds += ( newIds == '' ? '' : ',' ) + ids[i];
            newValues += ( newValues == '' ? '' : ',,' ) + values[i];
        }
    }

    $( '#' + control ).val( newIds );
    $( '#' + control + '_values' ).val( newValues );
}

function openWindowCentered( windowUrl, windowName, windowWidth, windowHeight, windowFeatures ){
    var left = Math.floor( ( window.screen.width - windowWidth ) / 2 );
    var top = Math.floor( ( window.screen.height - windowHeight ) / 2 );
    if ( windowFeatures != "" )
        windowFeatures = windowFeatures + ",";
    var features = windowFeatures + "resizable=1, " + " width=" + windowWidth + ", height=" + windowHeight + ", top=" + top + ", left=" + left;
    window.open( windowUrl, windowName, features );
    return false;
}

function linkObjectControlOnSelectButtonClick( lookupUrl, lookupHandler, listUrl, name, windowWidth, windowHeight )
{
    var bOpenSelectionWindow = false;

    if( lookupUrl && !$( '#' + name ).val() && $( '#' + name + 'Name' ).val() )
    {
        $.ajax(
            {
                async: false,
                type: "GET",
                url: lookupUrl + $( '#' + name + 'Name' ).val(),
                success:
                    function( data ){
                        bOpenSelectionWindow = data ? eval( lookupHandler + '( "'+ data + '", "' + name + '" )' ) : true;
                    }
            }
        );
    }

    else
        bOpenSelectionWindow = true;

    if ( bOpenSelectionWindow )
    {
        if ( !$( '#' + name ).val() )
            listUrl += $( '#' + name + 'Name' ).val();
        openWindowCentered( listUrl, '_blank', windowWidth, windowHeight, 'scrollbars=1' );
    }

    return false;
}

function linkObjectControlLookupHandler( res, name )
{
    var arRes = res.split(';');
    if ( arRes.length == 2 )
    {
        $( '#' + name ).val( arRes[ 0 ] );
        $( '#' + name + 'Name' ).val( arRes[ 1 ] );
        return false;
    }
    else
        return true;
}

function clearListObjectControl( name )
{
    $( '#' + name ).val( '' );
    $( '#' + name + 'Name' ).val( '' );
    return false;
}

function initToggle( id )
{
    var $dt = $( '#' + id + ' dt' );
    var $sign = $( '<span>+</span>' )
        .prependTo( $dt );
    var $dd = $( '#' + id + ' dd' )
        .hide();
    $dt.click(
        function(){
            if ( $dd.css( 'display' ) == 'none' )
                $dd.slideDown( 'fast', function(){ $sign.text( '-' ); } );
            else
                $dd.slideUp( 'fast', function(){ $sign.text( '+' ); } );
        }
    );
}

function fileControlSynchronize( current, toSynchronize )
{
    var dest = document.getElementById( current );
    var sourse = document.getElementById ( toSynchronize )

    if ( dest.value != sourse.value )
    {
        dest.value = sourse.value;
    }
}

/*function treeNodeChildrenToggle( nodeId, treeName, dataLoadedCallback )
{
    var jChild = $( '#' + treeName + '_' + nodeId + ' ul' );

    if ( !jChild[0] )
    {
        var onclick = $( '#' + treeName + '_' + nodeId ).attr( 'onclick' );
        $( '#' + treeName + '_' + nodeId ).removeAttr( 'onclick' );

        $.get( "tree-handler.aspx", { id: nodeId, url: $( '#' + treeName + '_url' ).val(), tree: treeName, activeId: $( '#' + treeName ).val() },
            function( data ){
                if ( data == 'No records found' )
                    treePlusMinusChange( nodeId, treeName, true );
                else {
                    $( '#' + treeName + '_' + nodeId ).append( data );
                    treePlusMinusChange( nodeId, treeName, false );
                    $( '#' + treeName + '_' + nodeId ).attr( 'onclick', onclick );
                }
                if ( dataLoadedCallback )
                    dataLoadedCallback.call( this, treeName, nodeId );
            }
        );
    }
    else
    {
        jChild.toggle();
        treePlusMinusChange( nodeId, treeName, false );
    }

    return false;
}*/

function treePlusMinusChange( nodeId, treeName, removeSign )
{
    var jImg = $( '#' + treeName + '_' + nodeId + '_control' );
    var src = jImg.attr( 'src' );
    jImg.attr( 'src',
        removeSign ?
            src.replace( 'plus|minus', 'shifter' ) :
            src.indexOf( 'plus' ) > -1 ?
                src.replace( 'plus', 'minus' ) :
                src.replace( 'minus', 'plus' )
    );
}

function treeInit( treeName, nodeId )
{
    var treeUnrollPath = $( '#' + treeName + '-path' ).val().split( '.' );

    for ( var i in treeUnrollPath )
    {
        if ( !nodeId || nodeId == treeUnrollPath[i-1] )
        {
            treeNodeChildrenToggle( treeUnrollPath[i], treeName, treeInit );
            break;
        }
    }
}

function ReturnUrlToFck( url ){
    window.opener.SetUrl( url );
    window.close();
    return false;
}

function ReturnSectionUrlToFck( url, sectionPart ){
    var re = /\?/g;
    if (re.test(url))
        url += '&' + sectionPart;
    else
        url += '?' + sectionPart;
    window.opener.SetUrl( url );
    window.close();
    return false;
}

function getFormattedDate( date, template )
{
    if ( ( typeof date == "object" ) && ( date instanceof Date ) )
    {
        template = template.replace( "yyyy", date.getFullYear() );
        template = template.replace( "yy", date.getYear() );

        if ( (date.getMonth()+1).toString().length < 2 )
            template = template.replace( "MM", "0" + (date.getMonth()+1) );
        else
            template = template.replace( "MM", (date.getMonth()+1) );

        template = template.replace( "M", (date.getMonth()+1) );

        if ( date.getDate().toString().length < 2 )
            template = template.replace( "dd", "0" + date.getDate() );
        else
            template = template.replace( "dd", date.getDate() );

        template = template.replace( "d", date.getDate() );

        if ( date.getHours().toString().length < 2 ){
            template = template.replace( "hh", "0" + date.getHours() );
            template = template.replace( "HH", "0" + date.getHours() );
        }
        else{
            template = template.replace( "hh", date.getHours() );
            template = template.replace( "HH", date.getHours() );
        }

        template = template.replace( "h", date.getHours() );
        template = template.replace( "H", date.getHours() );

        if ( date.getMinutes().toString().length < 2 ) {
            template = template.replace( "nn", "0" + date.getMinutes() );
            template = template.replace( "mm", "0" + date.getMinutes() );
        }
        else{
            template = template.replace( "nn", date.getMinutes() );
            template = template.replace( "mm", date.getMinutes() );
        }

        template = template.replace( "h", date.getMinutes() );
        template = template.replace( "m", date.getMinutes() );

        if ( date.getSeconds().toString().length < 2 )
            template = template.replace( "ss", "0" + date.getSeconds() );
        else
            template = template.replace( "ss", date.getSeconds() );

        template = template.replace( "s", date.getSeconds() );

        return template;
    }
}

function getDateFromString( sDate, sTemplate )
{
    var nPos;
    var sYear;
    var sMonth
    var sDay;
    var dtDate;

    nPos = sTemplate.indexOf("YYYY");
    if ( nPos == -1 ) nPos = sTemplate.indexOf("yyyy");
    sYear = sDate.substr( nPos, 4 );
    nPos = sTemplate.indexOf("MM");
    sMonth = sDate.substr( nPos, 2 );
    nPos = sTemplate.indexOf("DD");
    if ( nPos == -1 ) nPos = sTemplate.indexOf("dd");
    sDay = sDate.substr( nPos, 2 );

    dtDate = new Date( sYear, sMonth, sDay );

    nPos = sTemplate.indexOf("hh");
    if ( nPos == -1 ) nPos = sTemplate.indexOf("HH");
    if ( nPos > 0 ) dtDate.setHours( sDate.substr( nPos, 2 ) );
    nPos = sTemplate.indexOf("mm");
    if ( nPos > 0 ) dtDate.setMinutes( sDate.substr( nPos, 2 ) );
    nPos = sTemplate.indexOf("ss");
    if ( nPos == -1 ) nPos = sTemplate.indexOf("SS");
    if ( nPos > 0 ) dtDate.setSeconds( sDate.substr( nPos, 2 ) );

    return dtDate;
}

function fillColorPickerControl ( controlName, cell ) {
    document.getElementById( controlName + '-color-name' ).value = cell.title;
    document.getElementById( controlName ).value = '#' + getHexRGBColor( cell.style.backgroundColor );
    if (document.getElementById( controlName ).value == '#') document.getElementById( controlName ).value = '';
    document.getElementById( controlName + '-img-sample' ).style.backgroundColor = cell.style.backgroundColor;
    document.getElementById ( controlName + '-pallete' ).style.display = 'none';
}

function clearColor( controlName, e ) {
    document.getElementById( controlName + '-color-name' ).value = '';
    document.getElementById( controlName ).value = '';
    document.getElementById( controlName + '-img-sample' ).style.backgroundColor = '';
    document.getElementById ( controlName + '-pallete' ).style.display = 'none';
}

function showHideColorPallete ( controlName, e )
{
    var x = 0, y = 0;

    if (!e) e = window.event;

    if ( e.pageX || e.pageY )
    {
        x = e.pageX;
        y = e.pageY;
    }
    else if (e.clientX || e.clientY)
    {
        x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
        y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
    }

    pallete = document.getElementById ( controlName + '-pallete' );

    if ( pallete.style.display == 'none' || pallete.style.display == '' ){
        pallete.style.left = x - 40 + 'px';
        pallete.style.top = y + 'px';
        pallete.style.display = 'block';
    }
    else
        pallete.style.display = 'none';
}

function getHexRGBColor( color )
{
    color = color.replace(/\s/g,"");
    var aRGB = color.match( /^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);

    if(aRGB)
    {
        color = '';
        for ( var i=1; i<=3; i++ )
        color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');
    }
    else
    color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');

    return color.toUpperCase();
}

function fixPNG( element ) {
    fixPNGMode( element, 'image' )
}
function fixPNGCrop( element ) {
    fixPNGMode( element, 'crop' );
}
function fixPNGScale( element ) {
    fixPNGMode( element, 'scale' );
}
function fixPNGMode( element, sizingMethod )
{
    if ( /MSIE (5\.5|6).+Win/.test( navigator.userAgent ) )
    {
        var src;
        if ( element.tagName == 'IMG' )
        {
            if ( /\.png$/.test( element.src ) )
            {
                src = element.src;
                element.src = "img/spacer.gif";
            }
        }
        else
        {
            src = element.currentStyle.backgroundImage.match( /url\("(.+\.png)"\)/i )
            if ( src )
            {
                src = src[1];
                element.runtimeStyle.backgroundImage = "none";
            }
        }

        if ( src )
            element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader( src='" + src + "', sizingMethod='" + sizingMethod + "')";
    }
}

function incrementControlValue( id, delta, min, max )
{
    var controlValue = $( '#' + id ).val();

    var res = parseInt( controlValue );
    if ( res != controlValue )
        res = min;
    else
        res += delta;
    if ( res < min )
        $( '#' + id ).val( min );
    else if( res > max )
        $( '#' + id ).val( max );
    else
        $( '#' + id ).val( res );

    if ( document.getElementById( id ).onchange != undefined )
        document.getElementById( id ).onchange();
}

function decrementControlValue( id, delta, min, max )
{
    incrementControlValue( id, -delta, min, max );
}

function InitFckEditor( sName, Width, Height )
{
    var sBasePath = document.location.pathname.replace( /\/[^\/]*$/, '/script/fckeditor/' );

    var oFCKeditor = new FCKeditor( sName );
    oFCKeditor.BasePath = sBasePath;
    oFCKeditor.Height = Height;
    oFCKeditor.Width = Width;
    oFCKeditor.ReplaceTextarea();

    return oFCKeditor;
}

function changeLanguage( sNewLangPostfix, sControls, sLanguages )
{
    var sOldLangPostfix = getActiveLanguage( sLanguages );
    if ( sNewLangPostfix != sOldLangPostfix )
    {
        var ready = true;

        if( typeof (FCKeditorAPI) != "undefined" )
        {
            $( sControls.replace( /[^,]+/g, '#$&' ) ).each(
                function(){
                    var oEditor = FCKeditorAPI.GetInstance( this.id ) ;
                    if ( oEditor != null && oEditor.Status == 0 )
                        ready = false;
                }
            );
        }

        if( ready )
        {
            saveActiveLanguageTexts( sControls, sLanguages );
            showLanguageTexts( sNewLangPostfix, sControls );

            $( '#' + sOldLangPostfix ).parent().removeClass( 'activeTab' );
            $( '#' + sNewLangPostfix ).parent().addClass( 'activeTab' );
        }
    }
    return false;
}

function getActiveLanguage( sLanguages )
{
    return $( sLanguages.replace( /[^,]+/g, '.activeTab #$&' ) ).attr( 'id' );
}

function saveActiveLanguageTexts( sControls, sLanguages )
{
    var sOldLangPostfix = getActiveLanguage( sLanguages );

    $( sControls.replace( /[^,]+/g, '#$&' ) ).each(
        function(){
            jOld = $( '#' + this.id + "-" + sOldLangPostfix );
            jControl = $( '#' + this.id )

            var oEditor = ( typeof (FCKeditorAPI) != 'undefined'  ) && FCKeditorAPI.GetInstance( this.id );
            jOld.val( oEditor ? oEditor.GetHTML() : jControl.val() );
        }
    );
}

function showLanguageTexts( sNewLangPostfix, sControls )
{
    $( sControls.replace( /[^,]+/g, '#$&' ) ).each(
        function(){
            jNewHidden = $( '#' + this.id + '-' + sNewLangPostfix );
            $( this )
                .val( jNewHidden.val() )
                .addClass( jNewHidden.attr( 'validate-error' ) ? 'errorclass' : '' );

            $( this.parentNode.parentNode ).addClass( 'languageSelectionItem' );

            if( typeof (FCKeditorAPI) != "undefined" ) {
                var oEditor = FCKeditorAPI.GetInstance( this.id ) ;
                if ( oEditor && oEditor.EditingArea )
                    oEditor.SetHTML( jNewHidden.val() );
            }
        }
    );
}

function toggleOptionalControls( groupName, openedCaption, closedCaption ) {

    var trDisplayType = $.browser.msie ? 'block' : 'table-row';

    $( '#trig-' + groupName ).toggleClass( 'collapsed' );

    $( 'tr.' + groupName ).each(
        function(){
            if( $( this ).css( 'display' ) == trDisplayType )
            {
                $( this ).css( 'display', 'none' );
                $( '#capt-' + groupName ).text( closedCaption );
                $( '#' + groupName ).val( '' );
            }
            else
            {
                $( this ).css( 'display', trDisplayType );
                $( '#capt-' + groupName ).text( openedCaption );
                $( '#' + groupName ).val( '1' );
            }
        }
    );
}

var windowGeometry = {};

$(function(){
    if ( window.innerWidth ) {
        windowGeometry.getViewportWidth = function( ) { return window.innerWidth; };
        windowGeometry.getViewportHeight = function( ) { return window.innerHeight; };
        windowGeometry.getHorizontalScroll = function( ) { return window.pageXOffset; };
        windowGeometry.getVerticalScroll = function( ) { return window.pageYOffset; };
    }
    else if ( document.documentElement && document.documentElement.clientWidth ) {
        windowGeometry.getViewportWidth =
            function( ) { return document.documentElement.clientWidth; };
        windowGeometry.getViewportHeight =
            function( ) { return document.documentElement.clientHeight; };
        windowGeometry.getHorizontalScroll =
            function( ) { return document.documentElement.scrollLeft; };
        windowGeometry.getVerticalScroll =
            function( ) { return document.documentElement.scrollTop; };
    }
    else if ( document.body.clientWidth ) {
        // IE6 เมเลเว DOCTYPE
        windowGeometry.getViewportWidth =
            function( ) { return document.body.clientWidth; };
        windowGeometry.getViewportHeight =
            function( ) { return document.body.clientHeight; };
        windowGeometry.getHorizontalScroll =
            function( ) { return document.body.scrollLeft; };
        windowGeometry.getVerticalScroll =
            function( ) { return document.body.scrollTop; };
    }
    if ( document.body.scrollWidth ) {
        windowGeometry.getDocumentWidth =
            function( ) { return document.body.scrollWidth; };
        windowGeometry.getDocumentHeight =
            function( ) { return document.body.scrollHeight; };
    }
    else if ( document.documentElement && document.documentElement.scrollWidth ) {
        windowGeometry.getDocumentWidth =
            function( ) { return document.documentElement.scrollWidth; };
        windowGeometry.getDocumentHeight =
            function( ) { return document.documentElement.scrollHeight; };
    }
    windowGeometry.getClickX = function ( e ) {
        return windowGeometry.getHorizontalScroll() + e.clientX;
    }
    windowGeometry.getClickY = function ( e ) {
        return windowGeometry.getVerticalScroll() + e.clientY;
    }
});

function showPopup( properties, effects ){

    var $frame,
        $bg;

    var loadPopup = function() {
        var load = function() {
            $( properties.behaviour.closeButton, $frame[0].contentWindow.document ).click( removePopup );

            $( properties.behaviour.submitButton, $frame[0].contentWindow.document ).click( submitPopup );

            $( 'body' ).one( 'click', removePopup );
        }

        effects.onLoad ? effects.onLoad( $frame, load ) : load();

        if ( properties.behaviour.onLoad )
                properties.behaviour.onLoad( $frame );

    }

    var removePopup = function() {

        var clean = function() {
            $( 'body' ).unbind( 'click', removePopup );

            $frame.remove();
            if( $bg ) $bg.remove();
        }

        effects.onClose ? effects.onClose( $frame, clean ) : clean();
        return false;
    }

    var submitPopup = function()
    {
        $frame
            .unbind( 'load' )
            .load(
                function(){
                    if ( !$( '.errorclass', $( $frame )[0].contentWindow.document )[0] )
                    {
                        if ( properties.behaviour.onBeforeSubmit )
                            properties.behaviour.onBeforeSubmit( $frame );

                        removePopup();

                        if ( properties.behaviour.onSubmit )
                            properties.behaviour.onSubmit( $frame );
                    }
                    else
                        loadPopup();
                }
            )
    }

    var frameHTML = '<iframe ';
    for ( var attr in properties.attributes )
        frameHTML += attr + '="' + properties.attributes[attr] + '" ';
    frameHTML += '></iframe>';

    $frame = $( frameHTML )
        .load( loadPopup )
        .css( properties.presentation.css )
        .appendTo( 'body' );

    if ( properties.presentation.bgCss ) {
        $bg = $( '<div>' )
            .css( properties.presentation.bgCss )
            .appendTo( 'body' );
    }
    if ( effects.loadingImage ){
        var $loading = $( '<img src="' + effects.loadingImage + '" />' )
            .appendTo( 'body' )
            .load(
                function(){
                    $loading
                        .css( {
                            position: 'absolute',
                            top: windowGeometry.getVerticalScroll() + ( windowGeometry.getViewportHeight() - $loading.height() )/2,
                            left: windowGeometry.getHorizontalScroll() + ( windowGeometry.getViewportWidth() - $loading.width() )/2
                        } )
                }
            )
        $frame.load( function(){ $loading.remove() } );
    }

    return false;
}

function openAdjustedImageWindow( controlId, a )
{
    var url = a.href;
    url += '&image-brightness=' + $( '#' + controlId + '-brightness').val()
    + '&image-contrast=' + $( '#' + controlId + '-contrast').val()
    + '&crop-top-x=' + $( '#' + controlId + '-ctx').val()
    + '&crop-top-y=' + $( '#' + controlId + '-cty').val()
    + '&crop-bottom-x=' + $( '#' + controlId + '-cbx').val()
    + '&crop-bottom-y=' + $( '#' + controlId + '-cby').val()
    + '&image-saturation=' + $( '#' + controlId + '-saturation').val()
    + '&image-rotate=' + $( '#' + controlId + '-rotate').val();

    var openWindow = function( width, height ) {
        if( ( typeof showPopupCentered == "function" ) )
            showPopupCentered( url, width, height, 'applyBtn' );
        else
            window.open( url, this.target );
    }

    if ( url.indexOf( 'image-file-loader' ) > -1 )
    {
        var $image = $( '<img src="' + url + '"/>' )
            .appendTo( 'body' )
            .hide();
        if($.browser.opera)$image.onload=function(){if(this.readyState)this.onload=function(){return false};}
        $image.load( function() { openWindow( $( this ).width(), $( this ).height() ); $( this ).remove(); } );
    }
    else
        openWindow( 800, 600);
}

