/**
 *
 * @author      Taras Kushnir
 *
 */

var logoutPath= '/default/logout';
var global_mess= '';
var customEvents= {open:'open', close:'close', beforedestroy:'beforedestroy'};
var ajax_lock= false;
var checkbox_height= 15;
var color_right= '#e2e2e2';
var color_wrong= '#f33';

function validate()
{
    this.form= null;
    this.customFields= {};
    this.matchFields= {};
    this.buttons= [];
    this.messBox= null;
    this.align= false;
    this.messContainer= null;
    this.url= 0;
    this.data= 0;
    this.ifTyped= {};
    this.ifChecked= {};
    this.checkboxBgPosition= {};
    this.init= initialize;
    this.bind= bindFormSubmit;
    this.unbind= unbindFormSubmit
    this.filled= filledFields;
    this.same= sameFields;
    this.valid= validFields;
    this.send= sendForm;
    this.ajax= sendAjax;
    this.merge= mergeData;
    this.date= dateValidate;
    this.push= pushFields;
    this.postprocess= 0;
    this.keyCodes= {enter:13};
    
    function initialize(formId, customFields, matchFields, buttonsId, messBoxId, align, messContainerId, url, additionalData, postprocess)
    {
        this.form= formId;
        this.customFields= customFields;
        this.matchFields= matchFields;
        this.buttons= buttonsId;
        this.messBox= messBoxId;
        this.align= align;
        this.messContainer= messContainerId;
        this.url= url;
        this.data= additionalData;
        this.postprocess= postprocess;
        if (this.form != null)
        {
            var th= this;
            $('#' + this.form).find('input[type=text]:visible, input[type=password]:visible, textarea:visible,\
                input[type=text].mustbevisible, input[type=password].mustbevisible, textarea.mustbevisible').each(function()
            {
                th.ifTyped[$(this).attr('id')]= false;
            });
            $('#' + this.form).find('.checkbox').each(function()
            {
                th.ifChecked[$(this).attr('id')]= false;
                th.checkboxBgPosition[$(this).attr('id')]= {x:0, y:0};
                $(this).css('background-position', 'top left');
            });
        }
        this.bind();
    }
                
    function unbindFormSubmit()
    {
        if (this.form != null)
        {
            var th= this;
            $('#' + this.form).find('input[type=text], input[type=password], textarea').each(function()
            {
                $(this).val('').unbind();
                $(this).css('border-color', color_right);
            });
            $('#' + this.form).find('.checkbox').each(function()
            {
                $(this).unbind();
                $(this).css('border-color', color_right);
                $(this).css('background-position', 'top left');
            });
            for (var i= 0; i < this.buttons.length; i++)
            {
                $('#' + this.form).find('#' + this.buttons[i]).unbind();
            }
        }
    }
                
    function bindFormSubmit()
    {
        if (this.form != null)
        {
            var th= this;
            $('#' + this.form).find('input[type=text]:visible, input[type=password]:visible, textarea:visible,\
                input[type=text].mustbevisible, input[type=password].mustbevisible, textarea.mustbevisible').each(function()
            {
                var hint= (typeof(th.customFields[$(this).attr('id')]) != 'undefined') &&
                    (typeof(th.customFields[$(this).attr('id')][0]) != 'undefined') &&
                    (typeof(hints[th.customFields[$(this).attr('id')][0]]) != 'undefined')
                        ? hints[th.customFields[$(this).attr('id')][0]]
                        : '';
                $(this).val(hint).addClass('hint')
                    .bind('keydown', function(e)
                    {
                        if ((e.which == th.keyCodes.enter) && !e.ctrlKey && !e.altKey && !e.shiftKey && !/^textarea$/i.test(e.target.nodeName))
                        {
                            th.send();
                        }
                    }).bind('keyup', function(e)
                    {
                        if ((e.which != th.keyCodes.enter) && !e.ctrlKey && !e.altKey && !e.shiftKey)
                        {
                            th.ifTyped[$(this).attr('id')]= ($(this).val() != '') ? true : false;
                        }
                    }).bind('focus', function(e)
                    {
                        if (!th.ifTyped[$(this).attr('id')])
                        {
                            $(this).val('').removeClass('hint');
                        }
                    }).bind('blur', function(e)
                    {
                        if (!th.ifTyped[$(this).attr('id')])
                        {
                            $(this).css('border-color', color_right);
                            $(this).val(hint).addClass('hint');
                        }
                    });
            });
            $('#' + this.form).find('.checkbox:visible, .checkbox.mustbevisible').each(function()
            {
                $(this).hover(function(e)
                {
                    $(this).css('background-position',
                        Number(th.checkboxBgPosition[$(this).attr('id')].x) + 'px ' +
                        Number(th.checkboxBgPosition[$(this).attr('id')].y-= checkbox_height) + 'px');
                }, function(e)
                {
                    $(this).css('background-position',
                        Number(th.checkboxBgPosition[$(this).attr('id')].x) + 'px ' +
                        Number(th.checkboxBgPosition[$(this).attr('id')].y+= checkbox_height) + 'px');
                }).click(function(e)
                {
                    $(this).css('background-position',
                        Number(th.checkboxBgPosition[$(this).attr('id')].x) + 'px ' +
                        Number(th.checkboxBgPosition[$(this).attr('id')].y+=
                            !(th.ifChecked[$(this).attr('id')]^= true)
                                ? checkbox_height * 2
                                : -(checkbox_height * 2)) + 'px');
                });
            });
            for (var i= 0; i < this.buttons.length; i++)
            {
                $('#' + this.buttons[i]).click(function(e)
                {
                    th.send();
                });
            }
        }
        else
        {
            this.ajax({});
        }
    }

    function filledFields()
    {
        var filled= true;
        var th= this;
        $('#' + this.form).find('.required:visible').each(function()
        {
            filled= filled && th.ifTyped[$(this).attr('id')];
            if (th.ifTyped[$(this).attr('id')])
            {
                $(this).css('border-color', color_right);
            }
            else
            {
                $(this).css('border-color', color_wrong);
            }
        });
        $('#' + this.form).find('.mustbechecked:visible').each(function()
        {
            filled= filled && th.ifChecked[$(this).attr('id')];
            if (th.ifChecked[$(this).attr('id')])
            {
                $(this).css('border-color', color_right);
            }
            else
            {
                $(this).css('border-color', color_wrong);
            }
        });
        if (!filled)
        {
            showMess(this.messBox, this.align, this.messContainer, warningMess.notFilledFields);
        }
        return filled;
    }
    
    function sameFields()
    {
        var same= true;
        for (var field in this.matchFields)
        {
            var pattern= $('#' + this.matchFields[field]).val();
            if (same&= $('#' + field).val() == pattern)
            {
                $('#' + field).css('border-color', color_right);
            }
            else
            {
                $('#' + field).css('border-color', color_wrong);
                showMess(this.messBox, this.align, this.messContainer, warningMess.notSameFields);
                break;
            }
        }
        return same;
    }

    function validFields()
    {
        var valid= true;
        for (var field in this.customFields)
        {
            for (var i= 0; i < this.customFields[field].length; i++)
            {
                var pattern= this.customFields[field][i];
                if (valid&= patterns[pattern].test($('#' + field).val()) &&
                    ((pattern == 'Date') ? this.date($('#' + field).val()) : true) ||
                    !($('#' + field).hasClass('required') || this.ifTyped[field]))
                {
                    $('#' + field).css('border-color', color_right);
                }
                else
                {
                    $('#' + field).css('border-color', color_wrong);
                    showMess(this.messBox, this.align, this.messContainer, warningMess['notValid' + pattern]);
                    break;
                }
            }
            if (!valid)
            {
                break;
            }
        }        
        return valid;
    }

    function sendForm()
    {
        if (!this.filled() || !this.same() || !this.valid())
        {
            return;
        }
        
        var data= {};
        var th= this;
        $('#' + this.form).find('input[type=text]:visible, input[type=password]:visible, textarea:visible').each(function()
        {
            data[$(this).attr('id')]= th.ifTyped[$(this).attr('id')] ? $(this).val() : '';
        });
        $('#' + this.form).find('.checkbox:visible').each(function()
        {
            data[$(this).attr('id')]= th.ifChecked[$(this).attr('id')] ? 'checked' : '';
        });
        $('#' + this.form).find('.pseudo').each(function()
        {
            data[$(this).attr('id')]= $(this).val();
        });
        
        this.ajax(data);
    }
    
    function sendAjax(data)
    {
        if (this.url == null)
        {
            if (typeof(this.postprocess) == 'function')
            {
                this.postprocess([]);
            }
            return;
        }
        if (ajax_lock)
        {
            return;
        }
        
        hideMess(this.messBox, this.messContainer);
        var th= this;
        $.ajax(
        {
            type: 'post',
            url: th.url,
            data: th.merge(data, th.merge(th.data, {form: th.form})),
            dataType: 'json',
            success: function(data)
            {
                var mess= warningMess.error;
                if ((data != null) && (data.length != 0))
                {
                    if (typeof(data['message']) != 'undefined')
                    {
                        mess= data['message'];
                    }
                    else if ((typeof(data['success']) != 'undefined') && (data['success'] == 'true'))
                    {
                        mess= warningMess.none;
                    }
                }
                if (mess != warningMess.none)
                {
                    showMess(th.messBox, th.align, th.messContainer, mess);
                }
                else
                {
                    hideMess(th.messBox, th.messContainer);
                    if (typeof(th.postprocess) == 'function')
                    {
                        th.postprocess(data);
                    }
                }
            }
        });
    }
    
    function mergeData(data1, data2)
    {
        for (var attr in data2)
        {
            data1[attr]= data2[attr];
        }
        return data1;
    }
    
    function dateValidate(str)
    {
        // VALIDATE DATE ONLY IN FORMAT DD.MM.YYYY
        var valid= false;
        var day= Number(str.substr(0, 2));
        var month= Number(str.substr(3, 2)) - 1;
        var year= Number(str.substr(6));
        var date= new Date(year, month, day);
        if ((date.getDate() == day) && (date.getMonth() ==  month) && (date.getFullYear() == year))
        {
            valid= true;
        }
        return valid;
    }

    function pushFields(data)
    {
        for (var field in data)
        {
            var value= data[field];
            if ((typeof(value) != 'undefined') && (value != null) && (value != ''))
            {
                $('#' + this.form).find('#' + field).val(value).removeClass('hint');
                this.ifTyped[field]= true;
            }
        }
    }
}

function showMess(messBoxId, align, messContainerId, mess)
{
    $('#' + messContainerId).empty().append(mess);
    if (align)
    {
        var l= ($(document).width() - $('#' + messBoxId).width()) / 2;
        l= (l > 0) ? l : 0;
        $('#' + messBoxId).css('left', l);
    }
    $('#' + messBoxId).slideDown();
    $('#' + messContainerId).css('margin-top', ($('#' + messContainerId).parent().height() - $('#' + messContainerId).height()) / 2);
    setTimeout('$(\'#' + messContainerId + '\').show()', 500);
    $('#' + messBoxId).trigger(customEvents.open);
}

function hideMess(messBoxId, messContainerId)
{
    $('#' + messContainerId).hide();
    $('#' + messBoxId).fadeOut();
    $('#' + messBoxId).trigger(customEvents.close);
}

function showSignForm(header)
{
    var t= ($(window).height() - $('#sign_form').height()) / 2;
    t= (t > 0) ? t : 0;
    var l= ($(document).width() - $('#sign_form').width()) / 2;
    l= (l > 0) ? l : 0;
    $('#sign_form').css('top', t);
    $('#sign_form').css('left', l);
    $('#sign_form_header').empty().append(header);
    $('#cover').show();
    $('#sign_form').hide().slideDown();
    $('#sign_form_main').trigger(customEvents.open);
}

function hideSignForm()
{
    if ($('#sign_form_main').is(':visible'))
    {
        renew_captcha('captcha');
    }
    hideMess('error_message', 'error_message_text');
    $('#cover').hide();
    $('#sign_form').hide();
    $('#sign_form_main').trigger(customEvents.close);
}

function greet(mess)
{
    hideSignForm();
    hideMess('error_message', 'error_message_text');
    global_mess= mess;
    setTimeout('showMess(\'notification_message\', true, \'notification_message_text\', global_mess)', 500);
    setTimeout('hideMess(\'notification_message\', \'notification_message_text\')', 3500);
}

function renew_captcha(captchaId)
{
    $('#' + captchaId).attr('src', $('#' + captchaId).attr('src') + '&' + Math.floor(Math.random() * 10000));
}

function showBanner()
{
    var t= ($(window).height() - $('#bannerdiv').height()) / 2;
    t= (t > 0) ? t : 0;
    var l= ($(document).width() - $('#bannerdiv').width()) / 2;
    l= (l > 0) ? l : 0;
    $('#bannerdiv').css('top', t);
    $('#bannerdiv').css('left', l);
    t= t - $('#bannerdiv_close_cross').height() - 2;
    l= l + $('#bannerdiv').width() + 2;
    $('#bannerdiv_close_cross').css('top', t);
    $('#bannerdiv_close_cross').css('left', l);
    $('#cover, #bannerdiv_close_cross').click(removediv= function(e)
    {
        $('#bannerdiv').hide();
        $('#bannerdiv_close_cross').hide();
        $('#cover').hide();
        $(this).unbind('click', removediv);
    }).show();
    $('#cover').show();
    $('#bannerdiv').slideDown(100);
}

function showLoader()
{
    var t= ($(window).height() - $('#loader').height()) / 2;
    t= (t > 0) ? t : 0;
    var l= ($(document).width() - $('#loader').width()) / 2;
    l= (l > 0) ? l : 0;
    $('#loader').css('top', t);
    $('#loader').css('left', l);
    $('#loader_cover').show();
    $('#loader').show();
}

function hideLoader()
{
    $('#loader_cover').hide();
    $('#loader').hide();
}

function setCookie(name, value, expiredays)
{
    var exdate= new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie= name + '=' + escape(value) +
        ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString());
}

function getCookie(name, defaultvalue)
{
    var value= defaultvalue;
    if (document.cookie.length > 0)
    {
      var start= document.cookie.indexOf(name + '=');
      if (start != -1)
      {
        start= start + name.length + 1;
        var end= document.cookie.indexOf(';', start);
        if (end == -1)
        {
            end= document.cookie.length;
        }
        value= unescape(document.cookie.substring(start, end));
      }
    }
    return value;
}

$(document).ready(function()
{
    String.prototype.toMoney= function()
    {
        var delim= ',';
        var str= this.replace('.', delim);
        if (str.length == 0)
        {
            str= '0';
        }
        var pos= str.indexOf(delim);
        if (pos == -1)
        {
            str+= delim;
            pos= str.length - 1;
        }
        else if (pos == 0)
        {
            str= '0' + str;
            pos++;
        }
        for (var k= str.length - 1 - pos; k < 2; k++)
        {
            str+= '0';
        }
        return str.substring(0, pos + 3);
    }
    String.prototype.toInteger= function()
    {
        return (this != '') ? this : '0';
    }
    $(document).bind('ajaxStart', function(e)
    {
        ajaxLock= true;
        showLoader();
    });
    $(document).bind('ajaxStop', function(e)
    {
        setTimeout('ajaxLock= false', 500);
        hideLoader();
    });
    $(document).bind('ajaxError', function(e, r, s)
    {
        showMess('error_message', true, 'error_message_text', warningMess.connectionError);
    });
    $('.lang').each(function()
    {
        $(this).click(function(e)
        {
            $('#referer_form').find('#referer').val(location.href);
            $('#referer_form').attr('action', '/' + $(this).attr('id')).submit();
        });
    });
    $('#error_message_close_cross').click(function(e)
    {
        hideMess('error_message', 'error_message_text');
    });
    $('#notification_message_close_cross').click(function(e)
    {
        hideMess('notification_message', 'notification_message_text');
    });
    $('#sign_form_close_cross').click(function(e)
    {
        hideSignForm();
    });
    $('#cover').click(function(e)
    {
        hideSignForm();
    });
    $('#topmenu_exit').click(function(e)
    {
        $('#referer_form').find('#referer').val(location.href);
        $('#referer_form').attr('action', logoutPath).submit();
    });
    $('#contact_form_new_captcha').click(function(e)
    {
        renew_captcha('contact_form_captcha');
    });
    $('.tree_expand').click(function(e)
    {
        if ($(this).parent().find('.tree_content_outer').height() == 0)
        {
            $(this).parent().find('.tree_content_outer').stop().animate(
            {
                height: $(this).parent().find('.tree_content_outer').find('.tree_content_inner').height()
            }, 500);
            $(this).css('background-position', '0 -13px');
        }
        else
        {
            $(this).parent().find('.tree_content_outer').stop().animate({height: 0}, 500);
            $(this).css('background-position', 'top left');
        }
    });
});
