function init(chooser, allCities, allPids, allIndexes) 
{
    var bas_cal, dp_cal, ms_cal;    
    bas_cal = new Epoch('bas_cal','flat',$('bas_cal'));
    dp_cal  = new Epoch('ms_cal','popup',$('birthDate'));
    dp_cal  = new Epoch('dp_cal','popup',$('endDate'));
    ms_cal  = new Epoch('ms_cal','flat',$('ms_cal'),true);
    if(this.isIE){
        $('autoUpdate').checked = false;
    }
    checkAutoUpdate();
    checkSound();
    if($('country')!==null && $('country').value>0){
        var cityChooser = $("city");
        cityChooser.setStyle("display","block");
        var choice = $('country').options[$('country').selectedIndex].value;
        var choiceCity = $('city').options[$('city').selectedIndex].value;
        cityChooser.options.length = 0;
        s=0;
        for(var i in allCities) {
            if(allPids[i]!==choice){}else{
                if(choiceCity==allIndexes[i]){
                    cityChooser.options[s] = new Option(allCities[i], allIndexes[i], allIndexes[choiceCity], true);
                }
                else
                {
                    cityChooser.options[s] = new Option(allCities[i], allIndexes[i]);
                }
                s++;
            }
        }
    }
}

function insideInit(){
    var bas_cal, dp_cal, ms_cal;    
    bas_cal = new Epoch('bas_cal','flat',$('bas_cal'));
    dp_cal  = new Epoch('dp_cal','popup',$('birthDate'));
    ms_cal  = new Epoch('ms_cal','flat',$('ms_cal'),true);
}

function getCookie(){
    lastpost = Cookie.get('lastpost');
    els = $('main').getElements('input[name=action]');
    //alert(lastpost);
    //alert(els.getValue());
    if(els.getValue()!=lastpost){
        Cookie.set('lastpost', els.getValue(), {domain: false, path: '/', duration: 1});
    }
}                                                      

function checkemail(){
    email = $('login').value;
    val = (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
    err=0;
    if(val===false){
        alert('E-mail введен не корректно!');
        err=1;
    }
    if(err==0) $('formid').submit();
}

function checkAuthForm(){
    email = $('auth_login').value;
    pass = $('auth_pass').value;
    val = (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
    err=0;
    if(val===false || pass==''){
        alert('E-mail или пароль введены не корректно!');
        err=1;
    }
    if(err==0) $('formid').submit();
}

function checkAuthFormHeader(){
    email = $('auth_loginHeader').value;
    pass = $('auth_passHeader').value;
    val = (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
    err=0;
    if(val===false || pass==''){
        alert('E-mail или пароль введены не корректно!');
        err=1;
    }
    if(err==0) $('formidHeader').submit();
}

function checkRegisterForm(){
    email = $('login').value;
    name = $('name').value;
    fullname = $('fullname').value;
    pwd = $('pwd').value;
    cpwd = $('cpwd').value;
    birthDate = $('birthDate').value;
    //alert($('login').type);
    val = (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
    err=0;
    if(birthDate==''){
        alert('Дата рождения не корректна!');
        err=1;
    }
    if(val===false){
        alert('1E-mail введен не корректно!');
        err=1;
    }
    if(pwd=='' || pwd!=cpwd){
        alert('Либо пустой пароль либо они не сходятся');
        err=1;
    }
    if(name==''){
        alert('Псевдоним не должно быть пустым');
        err=1;
    }
    if(fullname==''){
        alert('Ф.И.О. не должно быть пустым');
        err=1;
    }
    if(err==0) $('formid').submit();
}

function changeHidden(id){
    if(!$('UL'+id)){
        //$('treeImg'+id).src = '/images/admin/gro.gif';
    }
    else
    {
        var val = $('UL'+id);
        if(val.getStyle("display")=='none'){
            val.setStyle("display", "block");
            //$('treeImg'+id).src = '/images/admin/gro.gif';
        }
        else
        {
            val.setStyle("display", "none");
            //$('treeImg'+id).src = '/images/admin/grc.gif';
        }
    }
}

function changeHiddenEditForm(id){
    if($('ULEF'+id)!=null){
        var val = $('ULEF'+id);
        if(val.getStyle("display")=='none'){
            val.setStyle("display", "block");
        }
        else
        {
            val.setStyle("display", "none");
        }
    }
}

function changeParentTree(id, parents, childs){
    specId = $('spec'+id);
    parentsArray = parents.split(",");
    childsArray = childs.split(",");
    
    if(specId.checked===false){
        if(childsArray.length>=1 && childsArray!=''){
            for(i=0;i<(childsArray.length);i++){
                $('spec'+childsArray[i]).checked = '';
            }
        }
    }
    
    if(specId.checked){
        if(parentsArray.length>1){
            for(i=0;i<(parentsArray.length);i++){
                $('spec'+parentsArray[i]).checked = 'checked';
            }
        }
    }
}

function addrow(el){
    var lrow=$(el).getPrevious().getPrevious().getPrevious();
    //alert(lrow);
    if(lrow.type=='hidden'){
        nrow=lrow.clone();
        nrow.type = 'file';
    }
    else
    {
        nrow=lrow.clone();
    }
    //alert(nrow);
    nrow.injectAfter(lrow);
}
function delrow(el){
    var lrow=$(el).getParent().getPrevious().getPrevious();
    //alert(lrow.type);
    if(lrow.type=='hidden'){}else{
        if(lrow!=null && lrow.src==''){
            nrow=lrow.remove();
        }
    }
}

function checkAddQueryForm(){
    err=0;
    price = $('price').value;
    countDays = $('countDays').value;
    query = $('query').value;
    fullQuery = $('fullQuery').value;

    priceTestes = (/^([0-9]+)$/i).test(price);
    countDaysTestes = (/^([0-9]+)$/i).test(countDays);

    if(query==''){
        alert('Запрос не должен быть пустым!');
        err=1;
    }
    if(fullQuery==''){
        alert('Полный запрос не должен быть пустым!');
        err=1;
    }
    if(priceTestes===false){
        alert('Цена введена не корректно!');
        err=1;
    }
    if(countDaysTestes===false){
        alert('Количество дней введено не корректно!');
        err=1;
    }
    
    
    if(err==0) $('formQuery').submit();
}

function checkSendMessageForm(){
    textValue = $('group').value;
    err=0;
    if(textValue==''){
        alert('Поле не должно быть пустым!');
        err=1;
    }
    if(err==0) $('sendMessageForm').submit();
}

function checkPass(){
    pwd = $('pwd').value;
    cpwd = $('cpwd').value;
    err=0;
    if(pwd=='' || pwd!=cpwd){
        alert('Либо пустой пароль либо они не сходятся');
        err=1;
    }
    if(err==0) $('formChangePass').submit();
}

function selectCountry(chooser, allCities, allPids, allIndexes){
    var cityChooser = $("city");
    cityChooser.options.length = 0;
    cityChooser.options[0] = new Option("Выберите город", "0", false, false);
    var choice = chooser.options[chooser.selectedIndex].value;
    var choiceCity = chooser.options[chooser.selectedIndex].value;
    //alert(choiceCity);
    if(choice != "" && choice != 0){
        cityChooser.setStyle("display","block")
        s=0;
        for(var i in allCities) {
            if(allPids[i]!==choice){}else{
                if(choiceCity==allIndexes[i]){
                    cityChooser.options[s] = new Option(allCities[i], allIndexes[i], allIndexes[choiceCity], true);
                }
                else
                {
                    cityChooser.options[s] = new Option(allCities[i], allIndexes[i]);
                }
                s++;
            }
        }
    }
    else
    {
        cityChooser.setStyle("display","none")
        cityChooser.options[0] = new Option("Выберите город", "0", false, true);
        for(var i in allCities) {
            cityChooser.options[i+1] = new Option(allCities[i], allIndexes[i]);
        }
    }    
}

function checkInt(){
    err=0;
    priceTestes = (/^([0-9]+)$/i).test($('price').value);
    if(priceTestes===false){
        alert('Цена введена не корректно!');
        err=1;
    }
    if(err==0) $('formOfferAdd').submit();
}
function reloadPage() {
    link = "http://"+$('serverNameLink').value+"/"+$('moduleNameLink').value+"_messages"+$('messagesLink').value+"_client"+$('clientLink').value+".html";
    this.location.replace(link);
}
                                   
function checkAutoUpdate(){
    name = 'autoupdate';
    value = 'on';
    //alert($('autoUpdate').checked);
    if($('autoUpdate')!== null && $('autoUpdate').checked === true){
        setCookie(name, value);
        setTimeout('reloadPage()', 1*10*1000); // интервал задается в миллисекундах
    }
    else
    {
        deleteCookie(name);
        clearTimeout();
    }
}

function checkSound(){
    name = 'checkSound';
    value = 'on';
    if($('getSound') !== null && $('getSound').checked === true){
        setCookie(name, value);
    }
    else
    {
        deleteCookie(name);
    }
}
function setCookie(name, value) {
    document.cookie = ""+name+"="+value+" expires=Wed, 1 Jan 2050 00:00:00";
}

function deleteCookie(name, value) {
    document.cookie = ""+name+"="+value+"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function getMessages(value){
    return value;
}

function checkSendConsultForm(){
    nameValue = $('name').value;
    priceValue = $('price').value;
    textValue = $('text').value;
    err=0;
    if(textValue==''){
        alert('Сообщение не должно быть пустым!');
        err=1;
    }
    if(priceValue==''){
        alert('Цена не должна быть пустой!');
        err=1;
    }
    if(nameValue==''){
        alert('Заголовок не должен быть пустым!');
        err=1;
    }
    if(err==0) $('sendConsultForm').submit();
}

/*-----------------------------------------------------------*/

function balance_calculate_result_amount(currency_id, action){
    if (currency_id != null) current_currency_id = currency_id;

    var amount = $('amount').value;

    var rate = rates[current_currency_id];

    var result_amount = 0;

    if (action == 'withdraw') result_amount = Math.round((amount * rate) * 100) / 100;
    else result_amount = Math.round((amount / rate) * 100) / 100;
    if (isNaN(result_amount)) result_amount = 0;
    else result_amount = Math.abs(result_amount);

    if (action == 'withdraw')
    {
        var title = titles[current_currency_id];

        $('result_amount').innerHTML = result_amount;
        $('result_title').innerHTML = title;
    }
    else $('result_amount').innerHTML = result_amount;
    if($('ye')!==null) $('ye').value = result_amount;
}

function moneyCheckFund(){
    amountValue = $('amount').value;
    amountValueTestes = (/^([0-9]+)(\.)?([0-9]+)?$/i).test(amountValue);
    err=0;
    if(amountValue=='' || amountValueTestes===false){
        alert('Некорректное поле!');
        err=1;
    }
    if(err==0) $('moneySaveFundForm').submit();
}

function withdrawCheckFund(){
    amountValue = $('amount').value;
    amountValueTestes = (/^([0-9]+)(\.)?([0-9]+)?$/i).test(amountValue);
    err=0;
    if(amountValue=='' || amountValueTestes===false){
        alert('Некорректное поле!');
        err=1;
    }
    if(err==0) {
        alert($('result_amount'));
        $('ye').value = $('result_amount');
        $('withdrawCheckFund').submit();
    }
}

function checkAccount(){
    var mas = new Array()
    mas[1] = "RUR";
    mas[2] = "USD";
    mas[3] = "EUR";
    accountValue = $('account').value;
    els = $('checkAccountForm').getFormElements();
    for(i=0;i<els.length;i++){
        if(els[i].checked===true){
            radioValue = els[i].value;
            break;
        }
    }
    err=0;
    if(mas[radioValue]=='RUR') accountValue = (/^R([0-9]+)$/i).test(accountValue);
    if(mas[radioValue]=='USD') accountValue = (/^Z([0-9]+)$/i).test(accountValue);
    if(mas[radioValue]=='EUR') accountValue = (/^E([0-9]+)$/i).test(accountValue);
    if(accountValue===false || accountValue==''){
        alert('Кошелёк введен не верно!');
        err=1;
    }
    if(err==0) $('checkAccountForm').submit();
}

function checkPayment(){
    err=0;
    priceTestes = (/^([0-9]+)$/i).test($('price').value);
    if(priceTestes===false){
        alert('Сумма в рублях!');
        err=1;
    }
    if(err==0) $('checkPaymentForm').submit();
}

function checkEditContractForm(){
    err=0;
    textValue = $('text').value;
    textareaValue = $('textarea').value;
    if(textValue==''){
        alert('Текст не может быть пустым!');
        err=1;
    }
    if(textareaValue==''){
        alert('Не может быть пустым!');
        err=1;
    }
    if(err==0) $('checkEditContractForm').submit();
}

function checkAddContractForm(){
    err=0;
    textValue = $('text').value;
    textareaValue = $('textarea').value;
    if(textValue==''){
        alert('Текст не может быть пустым!');
        err=1;
    }
    if(textareaValue==''){
        alert('Не может быть пустым!');
        err=1;
    }
    if(err==0) $('checkAddContractForm').submit();
}

function fastAddContract(){
    err=0;
    displayValue = $('checkAddContractForm').getStyle('display');
    if(displayValue=='none'){
        $('checkAddContractForm').setStyle('display', 'block');
    }
    else
    {
        $('checkAddContractForm').setStyle('display', 'none');
    }
}

function presentContract(){
    err=0;
    priceTestes = (/^([0-9]+)$/i).test($('price').value);
    if(priceTestes===false){
        alert('Цена введена не корректно!');
        err=1;
    }
    if(err==0) $('realizeContract').submit();
}

/* На входе ID выбранного элемента - не используется */

function checkboxUnique(id){
    els = $('checkPaymentForm').getFormElements();
    for(i=0;i<els.length;i++){
        if(els[i].type=='checkbox'){
            if(els[i].value==id){
                if($('contract'+id).checked === false){
                    els[i].checked = '';
                }
                else
                {
                    els[i].checked = 'checked';
                    $('contract').value = $('contract'+id).value;
                }
            }
            else
            {
                els[i].checked = '';
            }
        }
    }
}

function hideUnvalids(){
    //alert($('birthDate').getStyle('display'));
    if($('unvalidCode').getStyle('display')=='none'){
        //$('unvalidCode').setStyle('display', 'block');
    }
    else
    {
        //$('unvalidCode').setStyle('display', 'none');
    }
}
