/*
Copyright 2008-2011 by PE Eliseev Stanislav
The program is distributed under the terms of the GNU General Public License version 3.

This file is part of ForSiter http://forsiter.com

    ForSiter is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation version 3 of the License.

    ForSiter is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ForSiter.  If not, see <http://www.gnu.org/licenses/>.
 */

var oldvalue = [];

$ (function ()
{
    // вешаем тогглер на инпуты форм с классом togglable
    var allInputs = $ ("form.togglable :text, form.togglable :password, form.togglable textarea");
    for ( var i = 0; i < allInputs.length; i ++ ) {
        formId = $ (allInputs[ i ]).parents ('form').attr ('id');
        if ( !oldvalue[ formId ]) {
            oldvalue[ formId ] = new Array ();
        }
        oldvalue[ formId ][ $ (allInputs[ i ]).attr ('name') ] = $ (allInputs[ i ]).val ();
    }
    function toggleVal (event)
    {
        var target = $ (event.target);
        var formId = $ (target).parents ('form').attr ('id');
        switch (event.type) {
            case "focus" :
                if (target.val () == oldvalue[ formId ][ target.attr ('name') ])
                    target.val ('');
                break;
            case "blur" :
                if ( !target.val ()) {
                    target.val (oldvalue[ formId ][ target.attr ('name') ]);
                }
                break;
        }
        ;
    }
    $ ("form.togglable :text, form.togglable :password, form.togglable textarea").bind ('focus', toggleVal);
    $ ("form.togglable :text, form.togglable :password, form.togglable textarea").bind ('blur', toggleVal);
    // автозаполняющиеся поля
    $.fn.extend ({
        
        activate : function ()
        {
            return this.focus ().select ();
        }
    });
    // биндим клик по кнопке открыть форму
    $ (".openDialogForm").live ("click", function (e)
    {
        closeDialogForm ('fs-dialog-form');
        closeDialogForm ('fs-login');
        var sizes = $ (this).attr ('rel').split (",");
        var width = (parseInt (sizes[ 0 ]) != 0) ? parseInt (sizes[ 0 ]) : 100;
        var height = (parseInt (sizes[ 1 ]) != 0) ? parseInt (sizes[ 1 ]) : 100;
        $.post ($ (this).attr ('href'), {}, function (data)
        {
            $ (data).appendTo ("body");
            showDialogForm ('fs-dialog-form', width, height);
        });
        return false;
    });
    // биндим клик по кнопке закрыть
    $ (".closeDialogForm").live ("mousedown", function (e)
    {
        if ($ (this).hasClass ('fs-close')) {
            $ (this).removeClass ('fs-close-hover');
            $ (this).addClass ('fs-close-press');
        }
    });
    $ (".closeDialogForm").live ("mouseup", function (e)
    {
        if ($ (this).hasClass ('fs-close')) {
            $ (this).removeClass ('fs-close-press');
            $ (this).addClass ('fs-close-hover');
        }
        setTimeout ("closeDialogForm('fs-dialog-form');closeDialogForm('fs-login');", 200);
    });
    $ (".closeDialogForm").live ("mouseover", function (e)
    {
        if ($ (this).hasClass ('fs-close')) {
            $ (this).addClass ('fs-close-hover');
        }
    });
    $ (".closeDialogForm").live ("mouseout", function (e)
    {
        if ($ (this).hasClass ('fs-close')) {
            $ (this).removeClass ('fs-close-hover');
        }
    });
    var options = {
        success : onAjaxSubmitForm
    };
    // вешаем ajax form submit
    bindSimpleAjaxForm ();
    // добавляем затенение для всплывающих форм
    $ ('<div id="fs-shadow"></div>').css ({
        zIndex : 999,
        width : "100%",
        position : "fixed",
        top : 0,
        left : 0,
        opacity : 0.4,
        backgroundColor : "#000000"
    }).appendTo ("body").hide ();
    
    $ (document.body).keypress (function (e)
    {
        // убираем форму по нажатию escape
        if (e.keyCode == 27) {
            $ ('div[id^="fs_"]').each (function ()
            {
                closeDialogForm ($ (this).attr ('id'));
            });
        }
    });
    
    $ ('a.j_ajaxLink').click (function ()
    {
        $.post ($ (this).attr ('href'), {
            'postOn' : 'on'
        }, onAjaxSubmitForm);
        
        return false;
    });
    // инициализируем mp3players
    initMp3Player ();
    initFlvPlayer ();
});

function initMp3Player ()
{
    // подгузка аудиоплееров
    $ ("img.tinymce_audio_player").each (function ()
    {
        if ($ (this).attr ("title").replace (/\s/gi, "")) {
            // ищем рандомный id
            var i = 0;
            do {
                randomId = "tinymce_audio_player_" + Math.round ((Math.random (1, 1000) * 10));
                i ++ ;
            } while ($ ("#" + randomId).get (0) || i > 10);
            
            // устанавливаем рандомный id объекту
            $ (this).attr ('id', randomId).css ({
                zIndex : 100
            });
            
            // параметры для плей-листа
            title = $ (this).attr ('title');
            
            if (title.match (/^http:\/\/.*?/)) {
                protocol = 1;
            } else if (title.match (/^https:\/\/.*?/)) {
                protocol = 2;
            } else if (title.match (/^ftp:\/\/.*?/)) {
                protocol = 3;
            }
            
            file = title.replace ('http://', '').replace ('https://', '').replace ('ftp://', '');
            
            // url плей-листа
            playlistUrl = '/playlist.php?file=' + file + '&protocol=' + protocol;
            
            swfobject.embedSWF ("/flash/audio/mp3player.swf", randomId, "300", "100", "9.0.0", null, {}, {
                play : "true",
                menu : "false",
                loop : "true",
                wmode : "transparent",
                allowScriptAccess : "always",
                flashVars : "playlistURL=" + playlistUrl
            }, {});
            
        } else {
            $ (this).remove ();
        }
    });
}

function initFlvPlayer ()
{
    var randomId = "";
    $ ("img.tinymce_flv_player").each (function ()
    {
        
        do {
            randomId = "randomId" + Math.round (Math.random () * 100);
        } while ($ ("#" + randomId).length);
        
        $ ('<a id="' + randomId + '" />').attr ("href", $ (this).attr ("title")).css ({
            display : "block",
            width : $ (this).width (),
            height : $ (this).height ()
        }).insertAfter (this);
        
        $ (this).remove ();
        
        flowplayer (randomId, {
            src : "/flash/flv/flowplayer-3.0.3.swf",
            wmode : "opaque"
        }, {
            clip : {
                autoPlay : false,
                autoBuffering : true
            },
            plugins : {
                controls : {
                    url : '/flash/flv/flowplayer.controls-3.0.3.swf',
                    play : true,
                    volume : true,
                    mute : true,
                    time : false,
                    stop : false,
                    playlist : false,
                    fullscreen : true,
                    scrubber : true
                }
            },
            screen : {
                zIndex : 0
            }
        });
    });
}

function showShadow (zIndex)
{
    $ ("#fs-shadow").css ({"z-index": (zIndex - 1), "height": $ (document).height ()}).show ();
}

function hideShadow ()
{
    $ ("#fs-shadow").hide ();
}

function bindSimpleAjaxForm ()
{
    
    var options = {
        success : onAjaxSubmitForm,
        beforeSubmit : function (formdata, form)
        {
            if ( typeof validateFormVars == 'function') {
                return validateFormVars (formdata, form);
            } else {
                return true;
            }
        }
    };
    // вешаем ajax form submit
    $ ('form.simpleform').ajaxForm (options);
}

function validateFormVars (formdata, form)
{
    var formId = $ (form).attr ('id');
    // если форма является тогглабл
    if ($ (form).hasClass ('togglable')) {
        for (i = 0; i < formdata.length; i ++ ) {
            if (oldvalue[ formId ][ formdata[ i ].name ]) {
                if (oldvalue[ formId ][ formdata[ i ].name ] == formdata[ i ].value) {
                    formdata[ i ].value = '';
                }
            }
        }
    }
    return true;
}

// функция открытия диалоговой формв
function showDialogForm (formId, width, height, z_index)
{
    if ( !z_index)
        z_index = 1000;
    showShadow (z_index);
    var top = $ (document).scrollTop () + ($ (window).height () / 2 - height / 2);
    var left = $ (document).scrollLeft () + ($ (window).width () / 2 - width / 2);
    $ ('#' + formId).css ({
        top : top + 'px',
        left : left + 'px',
        width : width + 'px',
        height : height + 'px',
        display : "block",
        zIndex : z_index
    });
    // высота дива с контентом
    $ ('#' + formId + ' div.fs-scroll').css ('height', height - 84);
    // alert($('#' + formId + ' div.fs-scroll').css('height'));
    // делаем форму перемещаемой
    $ ('#' + formId).draggable ({
        handle : 'div.fs-dialog-form-head'
    });
    
    // опции для ajax submit form
    var options = {
        success : onAjaxSubmitForm
    };
    // вешаем ajax form submit
    $ ('form.dialogform').ajaxForm (options);
    
}
// функция закрытия диалоговой формв
function closeDialogForm (formId)
{
    $ ('#' + formId).removeShadow ();
    $ ('#' + formId).remove ();
    hideShadow ();
    return false;
}

function onAjaxSubmitForm (response, statusText, xhr, form)
{
    var responseJson = $.parseJSON (response);
    var $form = $ (form);
    $form.find ('.fs-error').empty ().hide();
	$form.find ('label').removeClass('error-msg');
    if (statusText == 'success') {
        if (responseJson.submitOn) {
            var formCallback = $form.attr ('callback');
            var callOn = false;
            if (responseJson.call) {
                closeDialogForm ('fs-dialog-form');
                try {
                    var call = responseJson.call + '(\'' + response + '\')';
                    eval (call);
                    callOn = true;
                } catch (e) {
                }
            }
            if (formCallback && !callOn) {
                closeDialogForm ('fs-dialog-form');
                try {
                    var call = formCallback + '(\'' + response + '\')';
                    eval (call);
                    callOn = true;
                } catch (e) {
                }
            }
            if (responseJson.redirectUrl && !callOn) {
                if (responseJson.openerOn) {
                    window.opener.location = responseJson.redirectUrl;
                    window.opener.location.reload ();
                    window.close ();
                } else {
                    window.location = responseJson.redirectUrl;
                }
            } else if (responseJson.reloadOn && !callOn) {
                window.location.reload ();
            } else if ( !callOn) {
                closeDialogForm ('fs-dialog-form');
            }
        }
        if (responseJson.errors) {
            if ($ ('#randomImage')) {
                $ ('#randomImage').attr ('src', '/antibot.php?u=' + Math.random ());
            }
            for ( var ctrlErr in responseJson.errors) {
                $ ('#err_' + $ (form).attr ('id') + '_' + ctrlErr).html (responseJson.errors[ ctrlErr ]).show ();
				$('label[for="'+ctrlErr+'"]').addClass("error-msg");
            }
        }
    }
}
// функция показа формы авторизации
function showAuthForm (data)
{
    closeDialogForm ('fs-login');
    $ (data).appendTo ("body");
    showDialogForm ('fs-login', 459, 293, 20000);
}

function openAuthForm (url)
{
    $.post (url, {
        t : (new Date).getTime ()
    }, showAuthForm);
}

function openContentEditor (linkobj)
{
    winobj = open ($ (linkobj).attr ('href'), "editor", "");
    winobj.focus ();
}

function toggleLoginForgotForms ()
{
    $ ("#fs-login-form").toggle ();
    $ ("#fs-forgot-form").toggle ();
    return false;
}

