/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/*
+check_mail(text) ++
+check_int(text) ++
+check_int_max(val,max_val)++
+check_phone(text)
+check_alpha(text) ++
+check_min_len(text, len) ++
+check_max_len(text, len) ++
+check_ip(text) ++
+check_user_pwd(text) ++
+check_admin_pwd(text) ++
+check_user_login(text) ++
+check_admin_login(text) ++
+trim(text) ++
+check_date(text) ++
+check_time(text) ++
+check_datetime(text) ++
+check_available_login(login) ++
+check_available_email(email,hz) ++
+format_amount ++
+check_login()
*/

function languageSimpleTranslate()
{
    if(typeof(window.langugage_data)!='undefined')
    {
        var i=0;
        var text="<body style='background-color:#D6F0FF;'><div align='center'><h1>Simple language editor</h1><form method='POST' action='"+base_url+"language_data/language_simple_translate/'><input type='submit'/><br/><table>";
        for(key in window.langugage_data)
        {
            
            text+="<tr "+(((i%2)==0)?"style='background-color:#ADDFFC;'":"")+">";
            text+="<td><{"+key+"}></td>";
            text+="<td ><textarea style='width:400px;' name='"+key+"'>"+Base64.decode(window.langugage_data[key])+"</textarea></td>";
            text+="</tr>";
            i++;
        }
        text+="</table><br/><input type='submit'/></form></div></body>";
        
        lang_win = window.open();
        lang_win.document.write(text);
    }
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


jQuery.fn.realBgColor=function()
{
    var col=this.css('backgroundColor');
    if(col=='transparent' || col=='')
    {
        this.parents().each(function(i,n){
            var c=$(n).css('backgroundColor');
            col=(col=='transparent' || col=='') ? c  : col;
        });
    }
    return col;
};

jQuery.fn.cssHash = function()
{
    var css1={};
    var str=this.attr('style');
    if(str!=undefined&&str!='')
    {
        var arr = str.split(';');
        for(key in arr)
        {
            var s=arr[key].split(':');
            if(s[0]!='')
            {
                var it=this.css($.trim(s[0]));
                if(it!=undefined)
                {
                    css1[$.trim(s[0])]=it;
                }                
            }
        }
    }
    return css1;
};

//Timer animation function
jQuery.fn.timerAnimate = function(callback)
{
    try{
        var s=$(this).html();
        /* if(typeof(callback)=='object')
        {
            pattern=callback['pattern'] ? callback['pattern'] : timer;
            timer=callback['timer'] ? callback['timer'] : timer;
            callback=callback['callback'] ? callback['callback'] : false;
        } */
        var myRe=/[0]*(\d{1,})(\D{1})[0]*(\d{1,})(\D{1})[0]*(\d{1,})|[0]*(\d{1,})(\D{1})[0]*(\d{1,})|[0]*(\d{1,})/;
        var a= myRe.exec(s);
        if(a instanceof Array)
        {
            if(!jQuery.timerAnimateParams)
            {
                jQuery.timerAnimateParams={};
            }
            
            var id=$(this).attr('id')?$(this).attr('id'):$(this).attr('id',"timerAnimate"+(""+Math.random()).substr(2));
            if(jQuery.timerAnimateParams[id])
            {
                clearInterval(jQuery.timerAnimateParams[id].pointer);
            }
            var n=new Date();
            jQuery.timerAnimateParams[id]={};
            jQuery.timerAnimateParams[id].pattern=((a[2]||'')+(a[4]||'')+(a[7]||''));
            jQuery.timerAnimateParams[id].date=new Date(n.getTime()+1000*(3600*(a[1]||0)+60*(a[3]||a[6]||0)+1*(a[5]||a[8]||a[9]||0)));
            jQuery.timerAnimateParams[id].callback=callback?callback:'';
            jQuery.timerAnimateParams[id].pointer=setInterval(function(){
                var n=new Date();
                var t=Math.round((jQuery.timerAnimateParams[id].date-n.getTime())/1000);
                if(t<0)
                {
                    clearInterval(jQuery.timerAnimateParams[id].pointer);
                    if(typeof(jQuery.timerAnimateParams[id].callback)=='function')
                    {
                        jQuery.timerAnimateParams[id].callback();
                    }
                    delete(jQuery.timerAnimateParams[id]);
                }
                else
                {
                    //console.log(t);
                    var h = Math.floor(t/3600);
                    var m = Math.floor((t%3600)/60);
                    var s = Math.floor((t%3600)%60);
                    var p=jQuery.timerAnimateParams[id].pattern;
                    
                    switch(p.length)
                    {
                    case 0:
                        x=(t<10?"0":"")+t;
                        break;
                    case 1:
                        var m = Math.floor(t/60);
                        var s = Math.floor(t%60);
                        var x = (m<10?"0":"")+m+p.charAt(0)+(s<10?"0":"")+s;
                        break;
                    case 2:
                        var h = Math.floor(t/3600);
                        var m = Math.floor((t%3600)/60);
                        var s = Math.floor((t%3600)%60);
                        var x = (h<10?"0":"")+h+p.charAt(0)+(m<10?"0":"")+m+p.charAt(1)+(s<10?"0":"")+s;
                        break;
                    }
                    var str=$('#'+id).html();
                    str=str.replace(myRe,x);
                    //console.log("s2: "+str);
                    $('#'+id).html(str);
                }
            }, 1000);
            
        }
    }catch(e){alert('timerView:'+print_r(e));}
}

//Timer animation function
function timerView(timer,elem,callback)
{
    try{
        if(timer==false)
        {
            var s=$(elem).html();
            var myRe=/((\d{1,2}):(\d{1,2}):(\d{1,2}))|((\d{1,2}):(\d{1,2}))|((\d{1,2}))/g;
            var arr= myRe.exec(s);
            if(arr instanceof Array)
            {
                timer=arr[0];    
            }
            else
            {
                timer="00:00:00";
            }
        }
        if(typeof(timer)!='number')
        {
            timer=timer.split(':');
            for(key in timer)
            {
                if(typeof(timer[key])!='function')
                {
                    var s=timer[key];
                    timer[key]=parseInt(s.indexOf('0')==0 ? s.substr(1) : s); 
                }                
            }
            timer=timer[0]*3600+timer[1]*60+timer[2];
        }
        
        if(isset(window.timerViewPointer) && isset(window.timerViewPointer.pointer))
        {
            clearInterval(window.timerViewPointer.pointer);
        }
        window.timerViewPointer={};
        window.timerViewPointer.timer=timer;
        window.timerViewPointer.view=elem;
        window.timerViewPointer.callback=isset(callback) ? callback :'';
        window.timerViewPointer.pointer=setInterval(function(){
            if(window.timerViewPointer.timer<=0)
            {
                clearInterval(window.timerViewPointer.pointer);
                if(typeof(window.timerViewPointer.callback)=='function')
                {
                    window.timerViewPointer.callback();
                }
                delete(window.timerViewPointer);
            }
            else
            {
                window.timerViewPointer.timer-=1;
                var t=window.timerViewPointer.timer;
                var h = Math.floor(t/3600);
                var m = Math.floor((t%3600)/60);
                var s = Math.floor((t%3600)%60);
                var x = (h<10?"0":"")+h+":"+(m<10?"0":"")+m+":"+(s<10?"0":"")+s;
                var str=$(window.timerViewPointer.view).html();
                var myRe=/((\d{1,2}):(\d{1,2}):(\d{1,2}))|((\d{1,2}):(\d{1,2}))|((\d{1,2}))/g;
                str=str.replace(myRe,x);
                $(window.timerViewPointer.view).html(str);
            }
        }, 1000);
    }catch(e){alert('timerView:'+print_r(e));}
}


function isset(obj)
{
    return (typeof(obj)!='undefined');
}

//Функция аналог print_r в PHP возвращает строку, принимает один обязательный параметр - обьект.
function print_r(arr,is_plain,deep,tabs,name)
{
    deep=deep?deep:6;
    tabs=tabs?tabs:"";
    name=name?"["+name+"]":typeof(arr);
    is_plain=is_plain?true:false;
    var separator=is_plain?"\n":"<br\>";
    
    var s=is_plain?"":"<pre>";
    s+=name+" =>\n"+tabs+"{\n";
    for(key in arr)
    {
        if(typeof(arr[key])=="object")
        {
            s+="\t"+tabs+print_r(arr[key],true,deep-1,tabs+"\t",key);
        }
        else
        {
            s+="\t"+tabs+"["+key+"] => ("+typeof(arr[key])+")"+arr[key]+",\n";
        }
    }
    s+=tabs+"}\n";
    s+=is_plain?"":"</pre>";
    return s;
} 

//Функция скроллинга документа до указанной позиции    
jQuery.scrollTopEx = function(endPosition,step,period){
    
    period=(typeof(period)!='undefined')?period:20;
    step=(typeof(step)!='undefined')?step:20;
    clearInterval(window.scrollTimer);
    window.scrollTimer = setInterval ("window.superScroll()", period);
    window.scrollStartPosition=$(document).scrollTop();
    window.scrollEndPosition= endPosition;
    window.superScroll=function()
    {
        window.scrollStartPosition-=step;
        if(window.scrollStartPosition<window.scrollEndPosition)
        {
            window.scrollStartPosition=window.scrollEndPosition;
            clearInterval(window.scrollTimer);
        }
        $(document).scrollTop(window.scrollStartPosition);
    }
}; 

function multiSelector()
{
    this.add=function(element,value,text)
    {
        if($("input#"+value).length!=0)
        {
            var temp=$("input#"+value).val();
            $("input#"+value).val('');
            value=temp;
        }
        text=(text!=undefined)?text:value;
        $("#"+element).html($("#"+element).html()+"\n<option value='"+value+"'>"+text+"</option>")
    };

    this.delSelected=function(element)
    {
        $("#"+element).children(":selected").remove();
    };

    this.selectAll=function(element)
    {
        $("#"+element).children().attr("selected",true);
    };

    this.validateAll=function(element,params,err_text,callback)
    {
        var v=FormValidator();
        v.add($("#"+element).attr('name'),params,err_text);
        this.selectAll;
        v.checkAll(callback);
    };

    this.getSelItems=function(element,separator)
    {
        var arr=new Array();
        $("#"+element).children(":selected").each(function(key,val){arr.push($(val).val());});
        return separator?arr.join(separator):arr;
    };

    this.getAllItems=function(element,separator)
    {
        var arr=new Array();
        $("#"+element).children().each(function(key,val){arr.push($(val).val());});
        return separator?arr.join(separator):arr;

    };
}


function messageFade(msg,is_error,period,fixed)
{
    var block='mess';
    var item='box';
    var pref='msg_';
    if(is_error)
    {
        block='mess_err';
        item='box_err';
        var pref='emsg_';
    }
    
    period=period?period:2000;
    $('.'+block).find('div.'+item).hide();            
    $('.'+block).find('div#'+pref+msg).show();            
    $('.'+block).fadeIn(period/2,function(){
        if(fixed===true)
        {
            $('.'+block).parent().height($('.'+block).height());
        }
    });
    $('.'+block).fadeOut(period/2,function(){
        $('.'+block).find('div.'+item).hide();
    });
}

//Функция отображения и скрытия боксов cообщений и ошибок;
function displayMessageEx(msg_arr, is_error,is_highlight)
{
    if((is_highlight==undefined&&window.global_highlight===true)||is_highlight===true)
    {
        var is_highlight=true;
    }
    var block='mess';
    var item='box';
    var pref='msg_';

    if(is_error)
    {
        block='mess_err';
        item='box_err';
        var pref='emsg_';
    }

    if(!window.new_box_counter)
    window.new_box_counter=0;
    var mess_set=$('div.'+block);
    
    
    //Скрытие сообщения с id указанным в is_highlight
    if(typeof(is_highlight)=='string')
    {
        var arr=new Array();
        mess_set.find('.'+item+'[@id!='+pref+is_highlight+']:visible').each(function(){
            arr.push(this.id.substring(pref.length));       
        });
        displayMessageEx(arr, is_error,false);    
        return;
    }
    
    var show_set=false;
    mess_set.show();
    
    mess_set.find('.r1,.r3').hide();
    
    if(msg_arr===false)
    {
        if(is_highlight)
        {
            highlightBox(false);  
        }
        else
        {
            mess_set.hide();        
        }
        return;
    }
    
    if(mess_set.find('.'+item).length<=0)
    {
        var l=mess_set.children().length;
        mess_set.children(':eq('+length/2+')').after(msg_arr);
    }

    mess_set.find('.'+item).hide();

    if(typeof(msg_arr)=='string')
    {
        msg_arr = [msg_arr]; //converting variable to array, containing the only value - by val petruchek
    }
    
    var temp_set=new Array();    
    for(msg in msg_arr)
    {
        if(typeof(msg_arr[msg])!='function')
        {
            if (isNaN(parseInt(msg_arr[msg])))
            {
                var temp=mess_set.find('#'+pref+msg_arr[msg]);
            }
            else
            {
                var temp=mess_set.find('.'+item+':eq('+parseInt(msg_arr[msg])+')');
            }

            if(temp.length>0)
            {
                temp_set.push(temp);
                show_set=true;
            }
            else
            {
                var temp=mess_set.find('.'+item+':last');
                var elem=temp.clone();
                elem.attr('id',"new_box_"+new_box_counter);
                elem.html(msg_arr[msg]);
                temp.after(elem);
                temp_set.push(elem);
                show_set=true;
                window.new_box_counter++;
                mess_set=$('div.'+block);
            }
        }
    }
    if(!show_set)
    {
        if(is_highlight)
        {
            highlightBox(block,false);  
        }
        else
        {
            mess_set.hide();        
        }
        return;
    }
    else
    {
        for(key in temp_set)
        {   
            if(typeof(temp_set[key])!='function')
            {
                temp_set[key].show();
            }
        }
        mess_set.find('.r1,.r3').show();
        
        if(is_highlight)
        {
            highlightBox(block);
            var topPos=mess_set.offset().top-10;
            if($(document).scrollTop()>topPos)
            {
                $.scrollTopEx(topPos);
            }			
        }   
    }
}

//Функция плавного отображения и скрытия боксов cообщений и ошибок;
function highlightBox(box_type,show)
{
    if(box_type===false||box_type===undefined||box_type=='mess_err')
    {
        var mess_set;
        mess_set=$('div.mess_err');
        var boxes=mess_set.find('.box_err:visible');
        if(boxes.length>0)
        {
            if(box_type===false||show===false)
            {
                boxes.fadeOut(1000);
                mess_set.find('.r1,.r3').fadeOut(1000);
            }
            else
            {
                boxes.fadeIn(1000);
                mess_set.find('.r1,.r3').fadeIn(1000);
            }
            
        }
    }
    if(box_type===false||box_type===undefined||box_type=='mess')
    {
        var mess_set;
        mess_set=$('div.mess');
        var boxes=mess_set.find('.box:visible');
        if(boxes.length>0)
        {
            if(box_type===false||show===false)
            {
                boxes.fadeOut(1000);
                mess_set.find('.r1,.r3').fadeOut(1000);
            }
            else
            {
                boxes.fadeIn(1000);
                mess_set.find('.r1,.r3').fadeIn(1000);
            }
        }
    }
}

//Класс валидации формы
function FormValidator()
{
    this.scan=function(selector)
    {
        if(isset(selector))
        {
            var range=$(selector);
            range=range.length>0 ? range : $('#'+selector);
            range = range.length==0 ? range : range.find(':input');
        }
        else
        {
            range=this.allFields.filter('.quickvalidator');
        }
        
        var obj=this;
        range.each(function(i,n){
            var classes=n.className.toString().split(/\s+/);
            var name=$(n).attr('name');
            var rules=new Array();
            if($(n).attr('name'))
            {
                if($(n).hasClass('qv_required'))
                {
                    rules["val"]=$("label[@for='"+name+"']>.add_field_error_text>.qv_required").html();
                }
                if($(n).hasClass('qv_numbers'))
                {
                    rules["check_int(val)||!val"]=$("label[@for='"+name+"']>.add_field_error_text>.qv_numbers").html();
                }
                if($(n).hasClass('qv_email'))
                {
                    rules["check_mail(val)||!val"]=$("label[@for='"+name+"']>.add_field_error_text>.qv_email").html();                
                }
                if($(n).hasClass('qv_phone'))
                {
                    rules["check_phone(val)||!val"]=$("label[@for='"+name+"']>.add_field_error_text>.qv_phone").html();        
                }
                if($(n).hasClass('qv_date'))
                {
                    rules["check_date(val)||!val"]=$("label[@for='"+name+"']>.add_field_error_text>.qv_phone").html();        
                }
                obj.add(name,rules);            
                obj.items[name].checkOnEvent("keyup");
                obj.items[name].checkOnEvent("click");
            }
        });                
    };
    
    this.allFields=$(':input');
    //Бордер вокруг поля
    this.border;

    //Событие на проверку поля добавляется только вновь добавленным полям
    this.onCheck;
    
    //Функция на нажатие кнопки Enter в любом поле валидатора
    this.submitter;

    //Добавление cобытия на проверку поля уже созданным и вновь добавленным полям
    this.setOnCheck=function(callback)
    {
        if(!callback||typeof(callback)=='function')
        {
            this.onCheck=callback;
            for(name in this.items)
            {
                if(typeof(this.items[name])!='function')
                {
                    this.items[name].onCheck=callback;
                }
            }
        }
        else
        {
            alert(callback+" is not a function!");
        }

    };

    //Массив полей
    this.items=new Array();

    //Стиль ошибок для всех полей
    this.error_style;

    //Добавление поля для валидации имя,параметры валидации, текст ошибки.
    this.add=function(name,params,err_text)
    {
        try{
            this.items[name]=new FormField(this,name,params,err_text);
            this.items[name].error.style=this.error_style?this.error_style:this.items[name].error.style;
            this.items[name].border=this.border?this.border:this.items[name].border;
            this.items[name].border=this.border===false?"":this.items[name].border;

            if(this.onCheck)
            {
                this.items[name].onCheck=this.onCheck;
            }
        }catch(e){alert("this.add: "+e.message);}
    };

    this.checkAll=function(callback)
    {
        //Проверить все поля, если callback задан - передать в check
        var result=true;
        try{
            for(key_name in this.items)
            {
                if(typeof(this.items[key_name])!='function')
                {
                    this.items[key_name].check(callback);
                    result=this.items[key_name].error['is_error']?!this.items[key_name].error['is_error']:result;
                }                
            }
        }catch(e){alert("checkAll: "+e.message);}
        return result;
    };
    
    //Функция проверки изменений 
    this.isChanged=function(names)
    {
        try{
            var temp_obj=isset(names) ? names : this.items;
            for(key_name in temp_obj)
            {
                if(typeof(temp_obj[key_name])!='function')
                {
                    key_name=isset(names) ? temp_obj[key_name] : key_name;
                    if(isset(this.items[key_name]) && typeof(this.items[key_name])!='function')
                    {
                        if(this.items[key_name].isChanged())
                        {
                            return true;
                        }
                    }
                }                
            }
        }catch(e){alert("isChanged: "+e.message);}
        return false;
    };
    
    this.reset=function(names)
    {
        try{
            var temp_obj=isset(names) ? names : this.items;
            for(key_name in temp_obj)
            {
                if(typeof(temp_obj[key_name])!='function')
                {
                    key_name=isset(names) ? temp_obj[key_name] : key_name;
                    if(isset(this.items[key_name]) && typeof(this.items[key_name])!='function')
                    {
                        this.items[key_name].reset();
                    }
                }                
            }
        }catch(e){alert("reset: "+e.message);}
    }

    //Функция получения массива значений полей
    this.getItems=function()
    {
        try{
            var arr=new Array();
            this.checkAll(false);
            for(key_name in this.items)
            {
                if(typeof(this.items[key_name])!='function')
                {
                    arr[key_name]=this.items[key_name].value;
                }
            }
            return arr;
        }catch(e){alert("getItems: "+e.message);}
    };
}

//Класс поля для валидации и получения значения (имя,параметры валидации, текст ошибки).
function FormField(parent,name,params,err_text)
{
    this.parent=parent;
    //Бордер вокруг поля
    this.border="1px #FF3333 solid";

    //Событие на проверку поля
    this.onCheck;

    //Функция получения текста ошибки из специального div формата  <div style="display:none;" id="emsg_name">Текст ошибки</div>
    this.getErrorText=function()
    {
        var name=this.name;
        return $("#emsg_"+name).text()?$("#emsg_"+name).text():"Error is not defined!";
    }

    //Имя поля на странице
    this.name=name;
    //Получение id поля
    
    this.id="";
    
    var t_elem=this.parent.allFields.filter("[@name='"+this.name+"']");
    if(t_elem.length==0)
    {
        t_elem=$(":input[@name='"+this.name+"']");
    }
    if(t_elem.length==0)
    {
        t_elem=$("[@name='"+this.name+"']");
    }
    
    var t_id=t_elem.attr('id');    
    
    if(t_id==undefined||t_id==""||t_id=="undefined")
    {
        this.id="field_"+this.name.split('[]').join('');
        t_id=t_elem.attr('id',this.id);        
    }
    else
    {
        this.id=t_id;
    }
    
    this.submitter=false;
    var this_elem=this;
    var obj=this.parent;    
    $('#'+this.id).keypress( function(event) {
        if(event.keyCode==13)
        {
            if(this_elem.submitter)
            {
                this_elem.submitter(event);
            }
            else if(obj.submitter)
            {
                obj.submitter(event);
            }            
        }
    } );
    
    //Массив параметров ошибки
    this.error = new Array();
    this.error['validation']=true;
    this.error['is_error']=false;
    this.error['text']=	err_text ? err_text : this.getErrorText();
    //Стиль в виде class="error_note" или style="color: #ff0000; font-size: xx-small;"
    this.error['style']='style="color: #ff0000; font-size: xx-small;"';

    
    if(typeof(params)=='object')
    {
        this.rules=params
        this.rule='extended';
    }
    else
    {
        //Правила валидации поля формат как для конструкции выбора IF пример: "check_int(val)&&check_max_len(val, 4)"
        this.rule=params;
    }
    
    //Значение поля
    this.value='';
    
    //Получение значения поля
    this.getValue = function()
    {
        var value="";
        try{
            var name=this.name;
            var elem=$('#'+this.id);
            //var elem=$('[@name='+name+']');
            var type=elem.attr('type');
            switch(type)
            {
            case 'checkbox':
                value=(elem.attr('checked'))?true:false;
                break;
            case 'radio':
                var elem=this.parent.allFields.filter('[@name='+this.name+']');    
                value=elem.filter(':checked').val()||"";
                break;
            default:
                value=elem.val()||"";
                break;
            }
            //value=addslashes(value);
        }catch(e){_sys_error("getValue:" , "FAIL",  e);}; 
        return value;
    }
    
    //Функция установки значения поля
    this.setValue=function(val)
    {
        this.value=val;
        $('#'+this.id).val(val);
        //$('[@name='+this.name+']').val(val);
    }
    
    //Установка исходного значения
    this.default_value=this.getValue();
    
    //Функция проверки изменений 
    this.isChanged=function()
    {
        var value=this.getValue();
        if((this.default_value instanceof Array))
        {
            if(this.default_value.length!=value.length)
            {
                return true;
            }
            for(key in this.default_value)
            {
                if(this.default_value[key]!=value[key])
                {
                    return true;
                }
            }
        }
        else
        {
            if(this.default_value!=value)
            {
                return true;
            }
        }
        return false;
    }
    
    //функция сброса значений
    this.reset=function()
    {
        this.setValue(this.default_value);
    }

    //Функция валидации поля и обработки ошибки с помощью функции обратного вызова (callback(name, val, error, show)), по умолчанию обрабатывается с помощью drawError(), если передать параметром false - ошибка не будет отображаться.
    this.check=function(callback)
    {
        //Проверить все поля, если callback задан - передать в check
        try{
            this.error['is_error']=false;
            var name_temp=this.name;
            name_temp=(typeof(name_temp)=="object") ? name.name : name_temp;
            var show = callback === false ? false : true;
            var error_text;
            var is_def=false;
            var flag=true;
            if(this.error['validation'])
            {
                flag = this.internalCheck();
            }
            error_text=this.error.text;
            if(!(typeof(callback) == 'function'))
            {
                error_text=callback?callback:error_text;
                callback = 'this.drawError';
                is_def=true;
            }
            show = flag ? false : show;
            try{
                eval((is_def?callback:"callback")+"('" + name_temp + "','" + addslashes(this.value) + "','" + addslashes(error_text) + "'," + show + ")");
            }catch(e){_sys_error("check->eval:" , "FAIL",  e);};
            if(this.onCheck)
            {
                this.onCheck();
            }
        }catch(e){alert("check: "+e.message);}
        return flag;
    };

    //Функция отображения или скрытия ошибки принимает строку или false или без параметров.
    this.showError=function (param, style, border)
    {
        try{
            var style_temp=this.error.style;
            if(style!=undefined&&style!=false)
            {
                this.error.style=style;
            }
            if(border!=undefined&&border==false)
            {
                new_style=old_style;
            }

            var name=this.name;
            name=(typeof(name)=="object") ? name.name : name;
            var show = param === false ? false : true;

            var error_text=this.error.text;
            error_text=param?param:error_text;
            var callback = 'this.drawError';

            eval(callback + "('" + name + "','" + addslashes(this.value) + "','" + addslashes(error_text) + "'," + show + ")");

            this.error['style']=style_temp;
            new_style="";

        }catch(e){alert("showError: "+e.message);}
    }

    //Функция валидации в ответ на событие принимает имя события в виде 'keyup'
    this.checkOnEvent=function (event,callback)
    {
        try{
            var obj=this;
            $('#'+obj.id).bind(event,function(){obj.check(callback);});
            //$('[@name='+obj.name+']').bind(event,function(){obj.check(callback);});
        }catch(e){alert("check: "+e.message);}
    };
    
    this.server=new Array();
    this.server.url="";
    this.server.params="";
    this.server.callback = function(data)
    {
        if(data['is_error'])
        {
            if(data['error_text']!="")
            {
                window.panelValidatorObject.items[data['name']].showError(data['error_text']);
            }
            else
            {
                window.panelValidatorObject.items[data['name']].showError();
            }
        }        
    };
    
    //Mетод валидатора для валидации на сервере.
    this.checkOnServer=function(url,params,event,callback)
    {
        this.server.url=url;
        this.server.params=params;
        if(typeof(callback)=='function')
        {
            this.server.callback=callback;
        }
        window.panelValidatorObject=this;
        if(typeof(event)=='undefined'||event==false)
        {
            serverCheck(this.name,this.value,'','');
        }
        else
        {
            this.checkOnEvent(event,serverCheck);
        }
    }
    
    
    
    
    //Функция валидации и отображения ошибок по умолчанию на сервере. (имя поля, значение поля, текст ошибки, флаг отображения ошибки)
    function serverCheck(name,value,error,show){
        try{
            if(isset(window.panelValidatorObject) && window.panelValidatorObject!=null && isset(window.panelValidatorObject.items) && isset(window.panelValidatorObject.items[name]))
            {
                
                if(!window.panelValidatorObject.items[name].check())
                {
                    return;
                }
                var params_arr = {'name':name};
                params_arr['value']=value;
                if(typeof(window.panelValidatorObject.items[name].server.params)=='object')
                {
                    for(key in window.panelValidatorObject.items[name].server.params)
                    {
                        params_arr[key]=window.panelValidatorObject.items[name].server.params[key];
                    }
                }
                on_post_message = function(msg)
                {
                    try{
                        var data;
                        data=getTempVarsSet(data,msg);	
                        for(key in data)
                        { 
                            if((typeof(data[key])!='function'))
                            {
                                data[key]['value']=Base64.decode(data[key]['value']);
                                if(window.panelValidatorObject.items[key].value==data[key]['value'])
                                {
                                    //Отображение текста ошибки переданной от сервера. 
                                    var error_text="";
                                    if(data[key]['error_text']!=undefined&&data[key]['error_text']!='')
                                    {
                                        if(temp_vars_set[data[key]['error_text']]!=undefined&&temp_vars_set[data[key]['error_text']]!='')
                                        {
                                            error_text=temp_vars_set[data[key]['error_text']];
                                        }
                                        else
                                        {
                                            var mess_set=$('div.mess_err');
                                            var temp=mess_set.find('#emsg_'+data[key]['error_text']);
                                            error_text=temp.text();                                
                                        }
                                    }
                                    data[key]['name']=key;
                                    data[key]['error_text']=error_text;                                
                                    window.panelValidatorObject.items[key].error.is_error=data[key]['is_error']; 
                                    try{
                                        window.panelValidatorObject.items[key].server.callback(data[key]);
                                    }catch(e){alert("window.panelValidatorObject.items['"+key+"'].callback("+window.panelValidatorObject.items[key].callback+"): "+e.message)};
                                }
                                else
                                {
                                    window.panelValidatorObject.items[key].check();
                                }
                            }
                            
                        }
                        return true;
                    }catch(e){alert(print_r(e.message))};
                };

                load_message(window.panelValidatorObject.items[name].server.url,params_arr);
            }
        }catch(e){alert("checkOnServer: "+e.message)};
    };

    //Внутрення функция валидации поля
    this.internalCheck=function ()
    {
        //Внутренняя функции валидации определенного поля
        try{
            var value=this.getValue();
            this.value=value;
            if(!(value instanceof Array))
            {
                value=new Array();
                value[0]=this.value;
            }
            for(key in value)
            {
                if(typeof(value[key])!='function')
                {
                    var val=value[key];
                    if(this.rule!=undefined && this.rule!=''&&!(this.error['is_error']))
                    {
                        try{
                            if(this.rule=="extended")
                            {
                                this.error['is_error']=false;
                                this.error['text']="";
                                for(rule in this.rules)
                                {
                                    if(typeof(this.rules[rule])!='function'&&!eval(addslashes(rule)))
                                    {
                                        this.error['is_error']=true;
                                        this.error['text']+=$("#emsg_"+this.rules[rule]).text() ? $("#emsg_"+this.rules[rule]).text() : this.rules[rule]+"<br/>";                                    
                                    }
                                }
                            }
                            else
                            {                        
                                this.error['is_error']=!eval(addslashes(this.rule));
                            }
                        }catch(e){alert(e.message)};
                    }
                }
            }
        }catch(e){_sys_error("internalCheck:" , "FAIL",  e);};
        return !this.error['is_error'];
    };


    //Внутренние переменные для временного хранения стилей
    var old_style = $('#'+this.id).attr('style');
    //var old_style = $('[@name='+this.name+']').attr('style');
    var new_style = "";
    //Функция отображения ошибок по умолчанию. (имя поля, значение поля, текст ошибки, флаг отображения ошибки)
    this.drawError = function (name, val, error, show)
    {
        try{
            // Функция отрисовки сообщения об ошибке - callback-функция по-умолчанию
            e = $("label[@for='"+name+"']");
            if(e.length > 0){
                if(e.find("#err_"+this.id).length > 0)
                {
                    if(e.find("#err_"+this.id).text() == error && show)
                    {
                        return;
                    }
                    e.find("#err_"+this.id).remove();
                    //Удаление красного бордера
                    if (old_style==undefined || old_style=="")
                    {
                        $('#'+this.id).removeAttr("style");
                        //$('[@name='+this.name+']').removeAttr("style");
                    }
                    else
                    {
                        $('#'+this.id).attr("style",old_style);
                        //$('[@name='+this.name+']').attr("style",old_style);
                    }
                }

                if(show)
                {
                    e.append('<div id="err_' + this.id + '" '+this.error.style+'>' + error + '</div>');
                    e.find("#err_"+name).text(error);
                    //Добавление красного бордера
                    //if($('[@name='+this.name+']').attr('style')!=new_style)
                    if($('#'+this.id).attr('style')!=new_style)
                    {
                        //old_style=$('[@name='+this.name+']').attr('style');
                        //$('[@name='+this.name+']').css({border:this.border});
                        //new_style=new_style?new_style:$('[@name='+this.name+']').attr('style');
                        
                        old_style=$('#'+this.id).attr('style');
                        $('#'+this.id).css({border:this.border});
                        new_style=new_style?new_style:$('#'+this.id).attr('style');
                    }
                }
            }
            else if(show)
            {
                displayMessageEx(error, true);
            }
        }catch(e){_sys_error("drawError:" , "FAIL",  e);};
    };

    //Функция экранирования симовлов
    function addslashes(str)
    {
        if(typeof(str)=='string')
        {
            str=str.replace(/\\/g,'\\\\');
            str=str.replace(/\'/g,'\\\'');
            str=str.replace(/\"/g,'\\"');
            str=str.replace(/\0/g,'\\0');
            str=str.replace(/\n/g,'\\n');
            str=str.replace(/\r/g,'\\r');
        }
        return str;
    }
}

function addslashes(str) {
if(typeof(str)=='string')
{
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\'/g,'\\\'');
            str=str.replace(/\"/g,'\\"');
str=str.replace(/\0/g,'\\0');
str=str.replace(/\n/g,'\\n');
str=str.replace(/\r/g,'\\r');
}
return str;
}


function check_url(val)
{
    var mask = /^([A-Za-z]+:\/\/){0,1}([a-zA-Z0-9][a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}[A-Za-z0-9:-_%&\?\/.=]+$/;
    return mask.test(val);
}

function check_extention(val)
{
    var mask=/^[^\\\/:;\*\?\"\<\>\'\|\.,&]+$/;
    return mask.test(val);
}


// Проверка целых чисел на максимальное и минимальное значение check_int_limit(value, max limit, min limit)
function check_int_limit(val,max_val,min_val)
{
    var re = /\d*/;
    var dot_re = /\./;
    var isDot = dot_re.test(val);
    var intval = parseInt(val, 10);
    var maxval = Infinity;
    if(max_val != false)
    {
        maxval = parseInt(max_val, 10);
    }
    var minval = parseInt(min_val, 10);
    if(isNaN(val) || !val || isDot)
    {
        return false;
    }
    else if((intval > maxval) || (intval < minval))
    {
        return false;
    }
    return true;
}

function check_int_max(val,max_val)
{
    var mval = parseInt(max_val);
    if(isNaN(val))
    {
        return false;
    }
    else if(val > mval)
    {
        return false;
    }
    return true;
}


function check_phone(phone)
{
    var mask=/^[-0-9()+ ]+$/;
    return mask.test(phone);
}

function check_date_format(text)
{
    var mask=/^[dDmMyY]{1}[-.\/]{1}[dDmMyY]{1}[-.\/]{1}[dDmMyY]{1}$/;
    if(mask.test(text)&&/[dD]{1}/.test(text)&&/[mM]{1}/.test(text)&&/[yY]{1}/.test(text)&&text.charAt(1)==text.charAt(3))
    {
        return true;
    }
    return false;
}

function compare_dates(d1, d2)
{
    var dt_from=convert_date(d1); 
    var dt_to=convert_date(d2);
    if( dt_from===false || dt_to===false )
    {
        return false;
    }    
    if(dt_from > dt_to) 
    {
        return false;
    }    
    return true;
}

function convert_date(text,date_format)
{
    date_format=date_format ? date_format : window.date_format;
    if(!check_date_format(date_format))
    {
        return false;
    }
    var df={'y':'1,4','m':'1,2','d':'1,2','s':date_format.charAt(1)};
    
    var f=date_format.toLowerCase().replace(new RegExp('['+df['s']+']{1}','g'),'');
    var mask=new RegExp("^[0-9]{"+df[f.charAt(0)]+"}["+df['s']+"]{1}[0-9]{"+df[f.charAt(1)]+"}["+df['s']+"]{1}[0-9]{"+df[f.charAt(2)]+"}$"); 
    if(!mask.test(text))
    {
        return false;
    }
    var da=text.split(df['s']);
    var dp={'y':parseInt(da[f.indexOf('y')],10),'m':parseInt(da[f.indexOf('m')],10),'d':parseInt(da[f.indexOf('d')],10)};
    //dp['y']=dp['y']<100 ? (dp['y']>30 ? dp['y']+1900 : dp['y']+2000) : dp['y'];
    dp['y']=dp['y']<100 ? dp['y']+2000 : dp['y'];    
    var dt=new Date(dp['y'],dp['m']-1,dp['d']);
    
    if(dt.getFullYear()!=dp['y'] || dt.getMonth()!=(dp['m']-1) || dt.getDate()!=dp['d'])
    {
        return false;
    }    
    return dt;
}

function check_date(text,date_format)
{
    return (convert_date(text,date_format)===false) ? false : true;    
}

function check_time(text)
{
    var mask=/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/;
    return mask.test(text);
}


function check_datetime(text)
{
    var mask=/^[0-9]{2}\.[0-9]{2}\.[0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}$/;
    return mask.test(text);
}

function check_mail(text)
{
    var mask = /^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9][a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$/;
    return mask.test(text);
}

function check_email_domain(text)
{
    var mask = /^([a-zA-Z0-9][a-zA-Z0-9-_]+\.)+[a-zA-Z]{2,6}$/;
    return mask.test(text);
}

function check_int(number)
{
    var mask=/^[0-9]+$/;
    return mask.test(number);
}

function check_amount(number)
{
    var mask=/^[0-9]+(\.[0-9]{0,2})?$/;
    return mask.test(number);
}

function check_alpha(text)
{
    var mask = /^[a-zA-Z]+$/;
    return mask.test(text);
}

function check_max_len(text, len)
{
    var strlen = parseInt(len);
    if(text.length>len)
    {
        return false;
    }

    return true;
}

function check_min_len(text, len)
{
    var strlen = parseInt(len);
    if(text.length<len)
    {
        return false;
    }

    return true;
}

function check_len(text,min,max)
{
    return (check_min_len(text, min) && check_max_len(text, max));
}

function check_ip(text)
{
    var mask = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
    if (!mask.test(text))
    {
        return false;
    }
    var bytes = mask.exec(text);
    return (bytes[1]<256) && (bytes[2]<256) && (bytes[3]<256) && (bytes[4]<256);
}

function check_ip_range(text)
{
    var mask1 = /^(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)$/;
    var mask2 = /^(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)-(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)\.(\d{1,3}|\*)$/;
    if (!mask1.test(text) && !mask2.test(text))
    {
        return false;
    }
    return true;
}

function check_user_pwd(text)
{
    var incorrect_symbols = /[^a-zA-Z0-9\!@#$%^&*=+\/~<>?;-]/;
    if( incorrect_symbols.test(text) )
    {
        return 0;
    }

    if(text.length<5)
    {
        return 0;
    }

    if( checkA(text) && checkB(text) && checkC(text) && checkD(text))
    {
        return 5;

    }

    if( checkA(text) && checkB(text) && (checkC(text) || checkD(text)))
    {
        return 4;
    }

    if( (checkA(text) || checkC(text)) && (checkB(text) || checkD(text)))
    {
        return 3;
    }

    if(checkA(text) || checkB(text) || checkC(text))
    {
        return 2;
    }

    return 0;
}

function check_admin_pwd(text)
{
    var incorrect_symbols = /[^a-zA-Z0-9\!@#$%^&*=+\/~<>?;-]/;
    if( incorrect_symbols.test(text) )
    {
        return 0;
    }

    if(text.length<7)
    {
        return 0;
    }

    if( checkA(text) && checkB(text) && checkC(text) && checkD(text))
    {
        return 5;

    }

    if( checkA(text) && checkB(text) && (checkC(text) || checkD(text)))
    {
        return 4;
    }

    if( (checkA(text) || checkC(text)) && (checkB(text) || checkD(text)))
    {
        return 3;
    }

    if(checkA(text) || checkB(text) || checkC(text))
    {
        return 2;
    }

    return 0;
}

function check_user_login(text)
{
    if(text.length<4)
    {
        return false;
    }
    var mask = /^[a-z].*/;
    if( mask.test(text) && ( checkA(text) || (checkB(text) || checkC(text)) ))
    {
        return true;
    }
    return false;
}

function check_admin_login(text)
{

    if(text.length<5)
    {
        return false;
    }
    var mask = /^[a-zA-Z].*/;
    if( !mask.test(text) )
    {
        return false;
    }

    return true;
}

function trim(text)
{
    if(text=='' || text=='undefined' || text == null || !text)
    {
        return '';
    }
    text = text.toString();
    return LTrim(RTrim(text));
}

function format_amount(num)
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    //      num = num.substring(0,num.length-(4*i+3))+','+
    num = num.substring(0,num.length-(4*i+3))+num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '' + num + '.' + cents);
}


function check_available_login(login)
{
    try
    {
        on_post_success=function(data)
        {
            if(data == 'true')
            {
                if(after_login_available_check)
                {
                    after_login_available_check(true);
                }
            }
            else
            {
                if(after_login_available_check)
                {
                    after_login_available_check(false);
                }
            }
        }
        on_post_error=function(data)
        {
            return false;
        }
        start_request(base_url+'user/check_available_login', {login:trim(login)});

    }
    catch(e)
    {

        _sys_error('check_available_login','',e);
    }

}

function check_available_email(email,domain_check)
{
    try
    {
        on_post_success=function(data)
        {
            if(data == 'true')
            {
                if(after_email_available_check)
                {
                    after_email_available_check(true);
                }
            }
            else
            {
                if(after_email_available_check)
                {
                    after_email_available_check(false);
                }
            }
        }
        on_post_error=function(data)
        {
            return false;
        }
        start_request(base_url+'user/check_available_email', {'email':trim(email),'domain_check':parseInt(domain_check)});

    }
    catch(e)
    {

        _sys_error('check_available_email','',e);
    }

}

function check_login(login)
{
    if(login.length<4)
    {
        return false;
    }

    if(login.length>64)
    {
        return false;
    }

    var incorrect_symbols = /[^_a-zA-Z0-9-]/;
    if( incorrect_symbols.test(login) )
    {
        return false;
    }

    var mask = /^[a-zA-Z].*/;
    if( mask.test(login) && ( checkA(login) || checkB(login) || checkC(login) ) )
    {
        return true;
    }
    return false;

}


// for password
function checkA(text,strong)
{
    var strong = parseInt(strong);
    if(strong==1)
    {
        var mask = /^[a-z]+$/;
    }
    else
    {
        var mask = /[a-z]+/;
    }
    return mask.test(text);
}
function checkB(text,strong)
{
    var strong = parseInt(strong);
    if(strong==1)
    {
        var mask = /^[0-9]+$/;
    }
    else
    {
        var mask = /[0-9]+/;
    }
    return mask.test(text);
}
function checkC(text,strong)
{
    var strong = parseInt(strong);
    if(strong==1)
    {
        var mask = /^[A-Z]+$/;
    }
    else
    {
        var mask = /[A-Z]+/;
    }
    return mask.test(text);
}
function checkD(text,strong)
{
    var strong = parseInt(strong);
    if(strong==1)
    {
        var mask = /^[\-!@#$%^&*=+\/~<>?;]+$/;
    }
    else
    {
        var mask = /[\-!@#$%^&*=+\/~<>?;]+/;
    }
    return mask.test(text);
}
// _for password


function LTrim(value)
{
    value = value.toString();
    if(value=='' || value=='undefined' || value == null || !value )
    {
        return '';
    }
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

function RTrim(value)
{
    value = value.toString();
    if(value=='' || value=='undefined' || value == null || !value )
    {
        return '';
    }
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}


function check_subscr_cancel_check()
{        
    hide_form_errors();
    
    if($('input[@name=ch]').val() != $('input[@name=ch_e]').val())
    {
        show_form_errors(2);            
        return false;
    }        
    return true; 
}

Date.prototype.print = function ( format ) {
            var a, jsdate=this;
            var pad = function(n, c){
                if( (n = n + "").length < c ) {
                    return new Array(++c - n.length).join("0") + n;
                } else {
                    return n;
                }
            };
            var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
                "Thursday","Friday","Saturday"];
            var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
            var txt_months =  ["", "January", "February", "March", "April",
                "May", "June", "July", "August", "September", "October", "November",
                "December"];
        
            var f = {
                // Day
                    d: function(){
                        return pad(f.j(), 2);
                    },
                    D: function(){
                        t = f.l(); return t.substr(0,3);
                    },
                    j: function(){
                        return jsdate.getDate();
                    },
                    l: function(){
                        return txt_weekdays[f.w()];
                    },
                    N: function(){
                        return f.w() + 1;
                    },
                    S: function(){
                        return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
                    },
                    w: function(){
                        return jsdate.getDay();
                    },
                    z: function(){
                        return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
                    },
        
                // Week
                    W: function(){
                        var a = f.z(), b = 364 + f.L() - a;
                        var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
        
                        if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                            return 1;
                        } else{
        
                            if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                                nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                                return this.date("W", Math.round(nd2.getTime()/1000));
                            } else{
                                return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                            }
                        }
                    },
        
                // Month
                    F: function(){
                        return txt_months[f.n()];
                    },
                    m: function(){
                        return pad(f.n(), 2);
                    },
                    M: function(){
                        t = f.F(); return t.substr(0,3);
                    },
                    n: function(){
                        return jsdate.getMonth() + 1;
                    },
                    t: function(){
                        var n;
                        if( (n = jsdate.getMonth() + 1) == 2 ){
                            return 28 + f.L();
                        } else{
                            if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                                return 31;
                            } else{
                                return 30;
                            }
                        }
                    },
        
                // Year
                    L: function(){
                        var y = f.Y();
                        return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
                    },
                    //o not supported yet
                    Y: function(){
                        return jsdate.getFullYear();
                    },
                    y: function(){
                        return (jsdate.getFullYear() + "").slice(2);
                    },
        
                // Time
                    a: function(){
                        return jsdate.getHours() > 11 ? "pm" : "am";
                    },
                    A: function(){
                        return f.a().toUpperCase();
                    },
                    B: function(){
                        // peter paul koch:
                        var off = (jsdate.getTimezoneOffset() + 60)*60;
                        var theSeconds = (jsdate.getHours() * 3600) +
                                        (jsdate.getMinutes() * 60) +
                                        jsdate.getSeconds() + off;
                        var beat = Math.floor(theSeconds/86.4);
                        if (beat > 1000) beat -= 1000;
                        if (beat < 0) beat += 1000;
                        if ((String(beat)).length == 1) beat = "00"+beat;
                        if ((String(beat)).length == 2) beat = "0"+beat;
                        return beat;
                    },
                    g: function(){
                        return jsdate.getHours() % 12 || 12;
                    },
                    G: function(){
                        return jsdate.getHours();
                    },
                    h: function(){
                        return pad(f.g(), 2);
                    },
                    H: function(){
                        return pad(jsdate.getHours(), 2);
                    },
                    i: function(){
                        return pad(jsdate.getMinutes(), 2);
                    },
                    s: function(){
                        return pad(jsdate.getSeconds(), 2);
                    },
                    //u not supported yet
        
                // Timezone
                    //e not supported yet
                    //I not supported yet
                    O: function(){
                    var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
                    if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
                    return t;
                    },
                    P: function(){
                        var O = f.O();
                        return (O.substr(0, 3) + ":" + O.substr(3, 2));
                    },
                    //T not supported yet
                    //Z not supported yet
        
                // Full Date/Time
                    c: function(){
                        return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
                    },
                    //r not supported yet
                    U: function(){
                        return Math.round(jsdate.getTime()/1000);
                    }
            };
        
            return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
                if( t!=s ){
                    // escaped
                    ret = s;
                } else if( f[s] ){
                    // a this.date exists: function
                    ret = f[s]();
                } else{
                    // nothing special
                    ret = s;
                }
        
                return ret;
            });
        }
