/**
 *  document    cm.dialog.js
 *  version     1.01
 *  contact     info@y21k.de
 *
 *  author		olaf zander
 *  copyright   (c) by y21k.de - all rights reserved.
 */
var Mailbox = (
    function () {
        var aSettings = {
            module : 'Mailbox',
            host : window.location.protocol +'//'+ window.location.host,
            path : {
                'root'       : '',
                'bin'        : '',
                'language'   : '',
                'template'   : '',
                'www'        : ''
            },
            filename : {
                'error' : 'syslog'
            },
            language : {
                'source' : new Array(),
                'target' : new Array()
            },
            regex : {
                'required' : new Array(),
                'regex'    : new Array(),
                'error'    : new Array()
            },
            session : null
        }

        function trim( sValue ) {
            if( typeof(sValue) == 'string' ) {
                return sValue.replace(/^\s+|\s+$/g, '');
            }
            return sValue;
        }

        function file_get_contents( sFile, sDataType, request, sType ) {
            var sContent = false;

            $.ajax({
                url      : sFile,
                type     : ( sType == 'get' ? 'get' : 'post' ),
                data     : request,
                dataType : sDataType,
                async    : false,
                success  : function( sData ) {
                    sContent = sData;
                },
                error    : function(XMLHttpRequest, textStatus, errorThrown){
                    var sMessages = '{time} File error: '+ sFile +' could not be loaded';

                    if( aSettings['debug.error'] != undefined ) {
                        if( aSettings['debug.error'] ) {
                            alert('File error 0: '+ sFile +' could not be loaded');
                        } else {
                            debug_writer(sMessages);
                        }
                    } else {
                        debug_writer(sMessages);

                        alert('File error 1: '+ sFile +' could not be loaded');
                    }
                }
            });
            return sContent;
        }

        function debug_writer( sMessage ) {
            $.post(aSettings.path.bin +'/debug-writer.php', {
                'filename' : aSettings.filename.error,
                'message'  : sMessage
            });
        }

        function set_settings_from_config( sContent, oSession ) {
            var aLines = sContent.split('\n');

            for(var n = 0; n < aLines.length; ++n ) {
                if( aLines[n] != '' ) {
                    var sLine   = aLines[n];
                    var aResult = sLine.split('=');

                    aResult[0] = trim(aResult[0]);
                    aResult[1] = trim(aResult[1]);
                    aResult[1] = ( aResult[1] == 'true' ? true : ( aResult[1] == 'false' ? false : aResult[1] ) );

                    if( aResult[0].search(/form.regex.+/) != -1 ) {
                        var aValidate = aResult[1].split('#');
                        var sName     = aResult[0].substr(aResult[0].lastIndexOf('.') +1);

                        aSettings.regex['required'][sName] = trim(aValidate[0]);
                        aSettings.regex['regex'][sName]    = trim(aValidate[1]);
                        aSettings.regex['error'][sName]    = trim(aValidate[2]);
                    } else {
                        aSettings[aResult[0]] = aResult[1];
                    }
                } else {
                    continue;
                }
            }
            aSettings.session = oSession;
        }

        function get_session( sKey ) {
            if( typeof(sKey) == 'string' ) {
                return aSettings.session[sKey];
            }
            return aSettings.session;
        }

        function set_session( sKey, sValue ) {
            aSettings.session[trim(sKey)] = trim(sValue);

            debug_session();
        }

        function debug_session() {
            if( aSettings['debug.session'] != undefined ) {
                if( aSettings['debug.session'] ) {
                    aSettings.session.$.debug();
                }
            }
        }

        function set_language_from_file() {
            var sLanguage = file_get_contents(aSettings.path.bin +'/cm.locale-load.php', '', 'locale='+ aSettings['language.code'], 'get');
            var oLanguage;

            if( window.DOMParser ) {
                oLanguage  = (new DOMParser()).parseFromString(sLanguage, 'text/xml');
            } else if( window.ActiveXObject ) {
                oLanguage = new ActiveXObject('Microsoft.XMLDOM');
                oLanguage.loadXML(sLanguage);
            }

            if( oLanguage ) {
                var oTransUnit = oLanguage.getElementsByTagName('transunit');

                if( oTransUnit.length == 0 ) {
                    var sMessages = '{time} Warning: XML element (transunit) not found';

                    debug_writer(sMessages);
                }

                for( var n = 0; n < oTransUnit.length; ++n ) {
                    var sSource = oTransUnit[n].getElementsByTagName("sources")[0].firstChild.nodeValue;
                    var sTarget = oTransUnit[n].getElementsByTagName("target")[0].firstChild.nodeValue;

                    aSettings.language.source[n]       = sSource;
                    aSettings.language.target[sSource] = sTarget;
                }
            }
        }

        function getText( sKey ) {
            if( typeof(sKey) == 'string' ) {
                return aSettings.language.target[sKey];
            }
            return aSettings.language;
        }

        function getLanguageKeys() {
            return aSettings.language.source;
        }

        function get_formular( sTemplate ) {
            var sReplace = null;
            var sPattern = null;
            var sForm = file_get_contents(aSettings.path.bin +'/cm.getTemplate.php', '', 'temp=form', 'get')

            if( aSettings['form.field.country.enable'] ) {
                var sOptions;

                if( typeof(get_session('country.options')) == 'string' && aSettings['cached.country'] ) {
                    sOptions = get_session('country.options');
                } else {
                    sOptions = file_get_contents(aSettings.path.bin +'/cm.getCountryOption.php', '', 'locale=', 'get');

                    if( aSettings['cached.country'] ) {
                        set_session('country.options', sOptions);
                    }
                }
                sPattern = eval('/{option}{\\/option}/g');
                sForm    = sForm.replace(sPattern, sOptions);
            }
            
            if( aSettings['form.label.type'] == 'symbol' ) {
                var aSource  = getLanguageKeys();

                for(var n = 0; n < aSource.length; ++n ) {
                    sPattern = '{lang}'+ aSource[n] +'{/lang}';

                    switch( aSettings['form.label.type'] ) {
                        case 'symbol':
                            sReplace = '<img src="'+ aSettings['dialog.themes'] +'/images/'+ ( aSource[n] == 'cm.dialog.email' ? aSource[n] : 'other' ) +'.gif" border="0" alt="'+ getText(aSource[n]) +'" title="'+ getText(aSource[n] +'.title') +'"/>';
                            break;
                        default:
                            break;
                    }
                    sForm = sForm.replace(sPattern, sReplace);
                }
            }
            sPattern = eval('/{form}{\\/form}/g');

            return sTemplate.replace(sPattern, sForm);
        }

        function append_dialog() {
            var sPattern  = null;
            var sTarget   = aSettings['dialog.append'];
            var sTemplate = file_get_contents(aSettings.path.bin +'/cm.getTemplate.php', '', 'temp=body', 'get')
                sTemplate = get_formular(sTemplate);

            /** translate **/
            var aSource  = getLanguageKeys();

            for(var n = 0; n < aSource.length; ++n ) {
                sPattern  = eval('/{lang}'+ aSource[n] +'{\\/lang}/g');
                sTemplate = sTemplate.replace(sPattern, getText(aSource[n]));
            }
            sPattern  = eval('/{themes}{\\/themes}/g');
            sTemplate = sTemplate.replace(sPattern, aSettings['dialog.themes']);

            $(sTarget).append(sTemplate);

            if( aSettings['form.label.type'] == 'symbol' ) {
                set_default_field_content();
                field_events();
            }
            set_max_width();

            // Drag abble
            if( aSettings['dialog.dragable'] ) {
                $('#cmDialogDragHandle .title').mousedown(function() {
                    draggable_events(true);
                    set_session('draggable', true);

                    $('#cmDialog').css("height", $('#cmDialog').height());
                });

                $('#cmDialogDragHandle .title').mouseup(function() {
                    draggable_events(false);
                });
            }
        }

        function draggable_events( draggable ) {
            $('#cmDialogDragHandle .title').css('cursor', 'pointer');

            if( draggable === false ) {
                $('#cmDialog').draggable('disable');

                return;
            }
            $('#cmDialog').draggable('enable');
            $('#cmDialog').draggable({containment: 'parent'});

            return;
        }

        function field_events() {
            var field = 'input';

            $('.cmDialogInput, textarea').focus(function () {
                var name  = $(this).attr('name');

                field = ( name == 'message' ? 'textarea' : 'input' );

                if( trim($(this).val()) == getText('cm.dialog.'+ name +'.title') ) {
                    $(this).val('');
                    $(this).removeClass('symbolFieldColor');
                } else {
                    $(this).removeClass('symbolFieldColor');
                }

            });
            $('.cmDialogInput, textarea').blur(function() {
                var name  = $(this).attr('name');

                field = ( name == 'message' ? 'textarea' : 'input' );

                if( trim($(this).val()) == '' || trim($(this).val()) == '-1' ) {
                    if( name == 'country' ) {
                        $('select[name=country] option[value="-1"]').text(getText('cm.dialog.country.title'))
                    } else {
                        eval('$(\''+ field +'[name='+ name +']\').val(getText(\'cm.dialog.'+ name +'.title\'))');
                    }

                    $(this).addClass('symbolFieldColor');
                } else {
                    $(this).removeClass('symbolFieldColor');
                }
            });
        }

        function set_default_field_content() {
            if( aSettings['form.field.country.enable'] ) {
                $('select[name=country] option[value="-1"]').text(getText('cm.dialog.country.title'))
            }
            $('input[name=name]').val(getText('cm.dialog.name.title'));
            $('input[name=email]').val(getText('cm.dialog.email.title'));
            $('input[name=subject]').val(getText('cm.dialog.subject.title'));
            $('textarea[name=message]').val(getText('cm.dialog.message.title'));

            $(".cmDialogInput, textarea").addClass('symbolFieldColor');
        }

        function hide_drag_handle_button() {
            var bExit   = aSettings['dialog.button.exit.enable'];
            var bMinMax = aSettings['dialog.button.minmax.enable'];

            if( !bMinMax ) {
                $('#cmDialogButtonMinMax').remove();
            }

            if( !bExit ) {
                $('#cmDialogButtonExit').remove();
            }

            if( bMinMax || bExit ) {
                return true;
            }
            return false;
        }

        function drag_handle_action_button() {
            /** disabled the dialog box for the domain **/
            $('#cmDialogButtonExit img').click(function() {
                $('#cmDialog').hide();

                set_session('cmDialogActive', false);
            });

            /** minimized or maximises the dialogue box for domain **/
            $('#cmDialogButtonMinMax img').click(function() {
                if( $("#cmDialogContentarea").is(":hidden") ) {
                    $("#cmDialogContentarea").slideDown();
                    $('.cmDialogContent').removeClass('cmDialogContentUp');
                    $('#cmDialogButtonMinMax img').attr('src', aSettings['dialog.themes'] +'/images/restore.gif');

                    if( get_session('draggable') == true ) {
                        $('#cmDialog').css("height", $('#cmDialog').height() +"px");
                    }
                    set_session('cmDialogActiveForm', true);
                } else {
                    /** set max width for the dialog **/
                    if( get_session('cmDialogWidth') == undefined ) {
                        var nWidth = $('#cmDialog').width();

                        set_session('cmDialogWidth', nWidth +4);
                    }

                    if( get_session('draggable') == true ) {
                        $('#cmDialog').css("height", "0px");
                    }
                    $('#cmDialogContentarea').slideUp();
                    $('#cmDialogContentarea').slideUp();
                    $('.cmDialogContent').addClass('cmDialogContentUp');
                    $('#cmDialogButtonMinMax img').attr('src', aSettings['dialog.themes'] +'/images/max.gif');

                    set_max_width();
                    set_session('cmDialogActiveForm', false);
                }
            });
        }

        function set_max_width() {
            if( get_session('cmDialogWidth') != undefined ) {
                $('#cmDialog').css('width', get_session('cmDialogWidth'));
            }
        }

        function set_position() {
            var sAlign    = trim(aSettings['dialog.position.align']);
            var sAlignPX  = trim(aSettings['dialog.position.align.px']);
            var sValign   = trim(aSettings['dialog.position.valign']);
            var sValignPX = trim(aSettings['dialog.position.valign.px']);

            if( sValign == 'top' ) {
                if( sAlign == 'left' ) {
                    $('#cmDialog').alignLeftTop(sValignPX, sAlignPX);
                } else {
                    $('#cmDialog').alignRightTop(sValignPX, sAlignPX);
                }
            }

            if( sValign == 'bottom' ) {
                if( sAlign == 'left' ) {
                    $('#cmDialog').alignLeftButtom(sValignPX, sAlignPX);
                } else {
                    $('#cmDialog').alignRightButtom(sValignPX, sAlignPX);
                }
            }
        }

        function show_dialog() {
            if( aSettings['dialog.show.onparams.enable'] ) {
                var aParams  = aSettings['dialog.show.onparams.where'].replace('&#61', '=').split(',');
                var sUrl     = window.location.href;

                for( var n = 0; n < aParams.length; ++n ) {
                    var sPattern = eval('/'+ trim(aParams[n]) +'/');

                    if( sUrl.search(sPattern) != -1 ) {
                        return true;
                    } else {
                        continue;
                    }
                }
                return false;
            }
            return true;
        }

        function disable_contextmenu() {
            var cm = document;

            if( aSettings['disable.contextmenu'] == 'dialog' ) {
                cm = '#cmDialog';
            }

            $(cm).bind("contextmenu", function(e) {
                return false;
            });
        }

        function set_please_wait( sDisplay, mOpacity ) {
            var oCSS = {
                'display'    : sDisplay,
                'background' : 'transparent url('+ aSettings['dialog.themes'] +'/images/please-wait.gif) center no-repeat',
                'width'      : $('#cmDialog').width(),
                'height'     : $('#cmDialog').height() -1
            }
            $('#cmDialogPleaseWait').css(oCSS);

            if( $.browser.msie ) {
                mOpacity = ( mOpacity == 1 ? 100 : mOpacity *100 );

                if( $.browser.version.substr(0,1) <= 7 ) {
                    $('#cmDialog table').css('filter','alpha(opacity='+ mOpacity +')');
                } else {
                    $('#cmDialog table').css('filter','"progid:DXImageTransform.Microsoft.Alpha(Opacity='+ mOpacity +')');
                }
            } else {
                $('#cmDialog table').css('opacity', mOpacity);
            }
        }

        function set_dialog_path( sPathDialog ) {
            var path = trim(sPathDialog);

            if( typeof(path) == 'string' && path != '' ) {
                if( path.substr(0, 1) == '/' ) {
                    path = path.substr(1);
                }

                if( path.substr(path.length -1, 1) == '/' ) {
                    path = path.substr(0, path.length -1);
                }
                path += '/'+ aSettings.module;
            } else {
                path = aSettings.module;
            }
            aSettings.path.root     = aSettings.host +'/'+ path;
            aSettings.path.www      = aSettings.path.root +'/www';
            aSettings.path.bin      = aSettings.path.root +'/application/bin';
            aSettings.path.language = aSettings.path.root +'/application/languages';
            aSettings.path.template = aSettings.path.root +'/application/templates';
        }

        function show_message(sKey)
        {
            var msg = getText(aSettings.regex['error'][sKey])
            var res = aSettings.regex['regex'][sKey].match(/[0-9]{1,}/g);
            var str = '';

            if( msg.search(/\$char/g) != -1 && sKey != 'form.regex.email' ) {
                for (var n = 0; n < res.length; ++n) {
                    str = msg.replace(/\$charmin/g, res[0]);

                    if( n == 1 && trim(res[1]) != '' ) {
                        str = str.replace(/\$charmax/g, res[1]);
                    }
                }
                alert(str);
            } else {
                alert(getText(aSettings.regex['error'][sKey]));
            }
        }

        return {
            Initialize: function( oSession, sPathDialog, sISO2 ) {
                set_dialog_path(sPathDialog);

                var sContent = file_get_contents(aSettings.path.bin +'/cm.dialog.php', '', 'action=true');

                if( sContent ) {
                    set_settings_from_config(sContent, oSession);

                    if( typeof(sISO2) == 'string' && trim(sISO2) != '' ) {

                        var sLocale = file_get_contents(aSettings.path.bin +'/cm.locale-check.php', '', 'locale='+ sISO2, 'get');

                        if( sLocale == 'ok' ) {
                            aSettings['language.code'] = sISO2;
                        }
                    }
                    aSettings['dialog.themes']= aSettings.path.www +'/css/'+ aSettings['dialog.themes'];

                    $('head').append('<link rel="stylesheet" type="text/css" href="'+ aSettings['dialog.themes'] +'/cm.dialog.css" >');

                    set_session('draggable', false);
                    debug_session();
                    set_language_from_file();

                    if( show_dialog() && get_session('cmDialogActive') ) {
                        append_dialog();

                        /** drag handle button **/
                        if( hide_drag_handle_button() ) {
                            drag_handle_action_button();
                        }
                        set_position();

                        if( aSettings['dialog.slide.in'] ) {
                            set_session('cmDialogActiveForm', false);
                        }

                        /** hide the contentarea **/
                        if( !get_session('cmDialogActiveForm') ) {
                            $('#cmDialogContentarea').css('display', 'none');
                            $('.cmDialogContent').addClass('cmDialogContentUp');
                            $('#cmDialogButtonMinMax img').attr('src', aSettings['dialog.themes'] +'/images/max.gif');
                        }

                        if( aSettings['dialog.slide.in'] ) {
                            $('#cmDialogButtonMinMax img').click();
                        }

                        if( !aSettings['form.label.textarea.enable'] ) {
                            $('#cmDialogContentarea .textarea').remove();
                            $('#cmDialogContentarea .textfield').attr('colSpan', 2);
                        }

                        if( !aSettings['form.field.country.enable'] ) {
                            $('#cmDialogContentarea .country').remove();
                        }
                        disable_contextmenu();
                    }
                }
            },

            Trim: function( sValue ) {
                return trim(sValue);
            },

            SendForm: function() {
                /** validate **/
                for( var sKey in aSettings.regex['regex'] ) {
                    if( !aSettings['form.field.country.enable'] ) {
                        aSettings.regex['required']['country'] = 'false';
                    }

                    if( aSettings.regex['required'][sKey] == 'true' ) {
                        var msg      = '';
                        var res      = '';
                        var str      = '';
                        var n        = 0;
                        var iserror  = false;
                        var sElement = eval('document.cmDialogContentarea.'+ sKey +'.value');
                        var regex    = new RegExp(aSettings.regex['regex'][sKey]);
                        var field    = ( sKey == 'message' ? 'textarea' : 'input' );

                        if( $(field +'[name='+ sKey +']').val() == getText('cm.dialog.'+ sKey +'.title') &&
                            aSettings.regex['required'][sKey] == 'true' &&
                            sKey != 'message') {
                            show_message(sKey);

                            eval('document.cmDialogContentarea.'+ sKey +'.focus();');

                            return false;
                        }

                        if (sKey == 'message') {
                            res = aSettings.regex['regex'][sKey].match(/[0-9]{1,}/g);

                            if(sElement.length >= res[0] && sElement.length <= res[1] ) {
                                break;
                            } else {
                                show_message(sKey);

                                eval('document.cmDialogContentarea.'+ sKey +'.focus();');

                                return false;
                            }
                        }

                        if( !sElement.match(regex) && sKey != 'message' ) {
                            if( aSettings['form.message.enable'] ) {
                                var oCSS = {
                                    'display' : 'block',
                                    'width': $('#cmDialog').width() -14
                                }

                                $('#cmDialogError').css(oCSS);

                                show_message(sKey);
                            } else {
                                show_message(sKey);
                            }
                            eval('document.cmDialogContentarea.'+ sKey +'.focus();');

                            return false;
                        }
                    }
                }

                if( aSettings['form.please.wait'] ) {
                    set_please_wait('block', 0.8);
                }

                var sRequest  = $("form").serialize();
                    sRequest += '&lang='+ aSettings['language.code'] +'&auth='+ aSettings['email.auth.code'] +'&type='+ aSettings['email.type'];

                $.ajax({
                    type    : "post",
                    url     : aSettings.path.bin +'/sendmail.php',
                    data    : sRequest,
                    async   : false,
                    success : function(sMessage) {
                        if( aSettings['form.message.enable'] ) {
                            $("#cmDialogError").ajaxComplete(function(event, request, settings) {
                                $(this).css('display', 'block');
                                $(this).html(getText(sMessage));
                            })
                        } else {
                            alert(getText(sMessage));
                        }

                        if( sMessage == 'cm.dialog.email.ok' ) {
                            $('.cmDialogInput').val('');

                            if( aSettings['dialog.button.minmax.enable'] ) {
                                $('#cmDialogButtonMinMax img').click();
                            }
                            set_default_field_content();
                        }
                    }
                });

                if( aSettings['form.please.wait'] ) {
                    set_please_wait('none', 1);
                }

                return false;
            }
        }
    }
)();

$.fn.alignLeftTop = function( pTop, pLeft ) {
    var attr   = {
        'position' : 'absolute',
        'top'      : parseInt(pTop)  +'px',
        'left'     : parseInt(pLeft) +'px'
    }
    this.css(attr);

    return this;
}

$.fn.alignRightTop = function( pTop, pRight ) {
    var attr   = {
        'position' : 'absolute',
        'top'      : parseInt(pTop)   +$(window).scrollTop()  +'px',
        'right'    : parseInt(pRight) +$(window).scrollLeft() +'px'
    }
    this.css(attr);

    return this;
}
$.fn.alignLeftButtom = function( pBottom, pLeft ) {
    var attr   = {
        'position' : 'absolute',
        'bottom'   : parseInt(pBottom) +'px',
        'left'     : parseInt(pLeft)   +'px'
    }
    this.css(attr);

    return this;
}
$.fn.alignRightButtom = function( pBottom, pRight ) {
    var attr   = {
        'position' : 'absolute',
        'bottom'   : parseInt(pBottom) +$(window).scrollTop()  +'px',
        'right'    : parseInt(pRight)  +$(window).scrollLeft() +'px'
    }
    this.css(attr);

    return this;
}


sPathDialog = Mailbox.Trim(sPathDialog);

var path      = sPathDialog;
var $sWebRoot = window.location.protocol +'//'+ window.location.host

if( typeof(path) == 'string' && path != '' ) {
    if( path.substr(0, 1) == '/' ) {
        path = path.substr(1);
    }

    if( path.substr(path.length -1, 1) == '/' ) {
        path = path.substr(0, path.length -1);
    }
    path  = $sWebRoot +'/'+ path +'/Mailbox';
} else {
    path = $sWebRoot +'/Mailbox';
}
document.writeln('<script type="text/javascript" src="'+ path +'/www/js/cm.session.js"></script>');

$(document).ready(function(){
    /** set default session vars **/
    if( oSession.cmDialogActive == undefined ) {
        oSession.cmDialogActive     = true;
        oSession.cmDialogActiveForm = true;
    }

    /** initialize the dialog box **/
    Mailbox.Initialize( oSession, sPathDialog, sISO2);

    //$('#cmDialogContentarea .cmDialogButton').click(function () {
      $("#cmDialogContentarea").submit(function() {
          return Mailbox.SendForm();
      });
    //});
});
