var HotLog = new Hash();
var site_id;
var check_url_retval;
var export_menu_status = 0;
var noti_period;
var discount_coupon = 0;

function check_newpass() {
    if($('new_password').value != $('new_password_check').value) {
	    $('new_password').value="";
	    $('new_password_check').value="";
	    alert("Введенные пароли не содпадают");
    }
    if($('new_password').value.length > 0 && $('new_password').value.length < 6) {
	    $('new_password').value="";
	    $('new_password_check').value="";
	    alert("Пароль не может быть менее 6 символов");
	    return;
    }
    else {
	    $('chpass_form').submit();
    }
}

function check_register() {
    if($('password_main').value != $('password_check').value) {
	    $('password_main').value="";
	    $('password_check').value="";
	    alert("Введенные пароли не содпадают");
	    return;
    }
    if($('password_main').value.length < 6) {
	    $('password_main').value="";
	    $('password_check').value="";
	    alert("Пароль не может быть менее 6 символов");
	    return;
    }
    if($('offer').checked == false) {
	    alert("Нужно принять соглашение");
	    return;
    }
    else {
	    $('regform').submit();
    }
}

function showInfoBlock(id) {
    if($(id+"_span").innerHTML == 'Подробнее') {
	    $(id).show();
	    $(id+"_span").innerHTML="Скрыть описание";
    }
    else {
	    $(id).hide();
	    $(id+"_span").innerHTML="Подробнее";
    }
}

function showDescBlock(id) {
    if($(id+"_span").innerHTML == 'Описание') {
	    $(id).show();
	    $(id+"_span").innerHTML="Скрыть";
    }
    else {
	    $(id).hide();
	    $(id+"_span").innerHTML="Описание";
    }
}

function desc_block_switch(id) {
    if($(id).readAttribute('visible') == 1) {
	    $(id).hide();
	    $(id).writeAttribute('visible', 0);
	    return false;
    }
    else {
	    $(id).show();
	    $(id).writeAttribute('visible', 1);
	    return false;
    }
}

function delete_site(id, url) {
    if(confirm("Вы уверены что вы хотите удалить сайт " + url)) {
	   $('delsite_id').value = id;
	   $('delsite_form').submit();
    }
}

function setHP(obj, url) {
    if (document.all) {
        obj.style.behavior='url(#default#homepage)';
        obj.setHomePage(url);
        return false;
    }
    else if(!document.layers) {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesWrite");
        navigator.preference("browser.startup.homepage", url);
        return false;
    }
    return true;
}

function check_my_counter(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    new Ajax.Request(
        '/counters',
          {
             method: 'get',
             parameters: { id: id, check_my_code: 1, rand: randpar },

             onSuccess: function(oReq) {
                eval('data=' + oReq.responseText);
                if(data.status == "0") {
                    $('cmc_answer').update(": Некорректный url " + data.url);
                }
                if(data.status == "1") {
                    $('cmc_answer').update(": " + data.url + " - код счётчика корректный.");
                }
                if(data.status == "2") {
                    $('cmc_answer').update(": " + data.url + " - код счётчика установлен в измененном виде. Работа всех статистических отчетов НЕ гарантируется.");
                }
                if(data.status == "3") {
                    $('cmc_answer').update(": " + data.url + " - код счётчика отсутствует.");
                }
             },
             onFailure: function () { }
          }
     );
}

function openPic(path,w,h) {
    window.open(path,'_blank','width='+w+',height='+h+',toolbar=0,titlebar=0,menubar=0,scrollbars=0,resizeable=0,status=0');
}

function show_qs() {
    $('query_string_span').show();
    $('qs_href').hide();
}

function select_counter(id) {
    for(var i=1;i<16;i++) {
	    bid = "counter_type_"+i;
	if($(bid))
	    $(bid).hide();
    }
    if($('switch_type_td'))
	    $('switch_type_td').hide();
        $('default_counter_select').show();
        $('selected_counter_td').show();
    if(id<200 || id>=300) {
	    $('selected_counter_div').innerHTML = '<img src="/images/counters/'+id+'.gif" width="88" height="31" border="0">';
    }
    else {
	    $('selected_counter_div').innerHTML = '<img src="/images/counters/'+id+'.gif" width="88" height="100" border="0">';
    }
    $('input_counter_id').value = id;
    $('selected_counter_td').setStyle({ width: '180px'});
    return false;
}
function show_counter_code(id) {
    for(var i=1;i<16;i++) {
	    bid = "counter_type_"+i;
	    if($(bid))
	        $(bid).hide();
    }
    if($('switch_type_td'))
	    $('switch_type_td').hide();
    $('default_counter_select').show();
    $('selected_counter_td').show();
    if(id<200 || id>=300) {
	    $('selected_counter_div').innerHTML = '<img src="/images/counters/'+id+'.gif" width="88" height="31" border="0">';
	    $('cheight_1').innerHTML = 31;
	    $('cheight_2').innerHTML = 31;
    }
    else {
	    $('selected_counter_div').innerHTML = '<img src="/images/counters/'+id+'.gif" width="88" height="100" border="0">';
	    $('cheight_1').innerHTML = 100;
	    $('cheight_2').innerHTML = 100;
    }
    $('counter_id_1').innerHTML = id;
    $('counter_id_2').innerHTML = id;
    $('selected_counter_td').setStyle({ width: '180px'});
    $('counter_code_table').show();
    return false;
}
function counter_type(t) {
    if(t == 0) {
	    for(var i=1;i<16;i++) {
	        bid = "counter_type_"+i;
	        if($(bid))
		        $(bid).hide();
	    }
	    if($('switch_type_td'))
	        $('switch_type_td').hide();
	    $('default_counter_select').show();
	    $('selected_counter_td').show();
	    $('selected_counter_td').setStyle({ width: '180px'});
    }
    else {
  	    $('default_counter_select').hide();
	    $('selected_counter_td').hide();
	if(t)
	    $('counter_type_'+t).show();
	if($('switch_type_td'))
	    $('switch_type_td').show();
    }
    return false;
}

function new_check_register(pid) {
    var error = 0;
    if($('sitename').value.length < 1) {
	    $('sitename_error').update("Ошибка: не введено название сайта");
	    $('sitename_error_block').show();
	    error++;
    }
    else {
	    $('sitename_error_block').hide();
    }
    if($('site_url_input').value == 'http://') {
	    $('siteurl_error').update("Ошибка: не введен URL сайта");
	    $('siteurl_error_block').show();
	    error++;
    }
    else {
	    var url = $('site_url_input').value;
	    var reg = /^http:\/\//;
	    var result = url.replace(reg, '');
	    if(result.length < 4) {
	        $('siteurl_error').update("Ошибка: не введён URL сайта");
	        $('siteurl_error_block').show();
	        error++;
	    }
	    else {
	        $('siteurl_error_block').hide();
	    }
    }
    if(! $('input_counter_id').value) {
	    $('counter_error').update("Ошибка: не выбран тип счётчика");
	    $('counter_error_block').show();
	    return;
    }
    else
	    $('counter_error_block').hide();
    if(error > 0)
	    return;
    if(!$('password_main') && !$('offer')) {
	    if(check_url() != 1) {
    	    if(!confirm($('site_url_input').value + " недоступен. Проверьте, нет ли ошибки в адресе сайта. Для продолжения регистрации нажмите OK.")) {
		        return;
	        }
	    }
	    $('regform').submit();
	    return;
    } 
    if($('password_main').value != $('password_check').value) {
	    $('password_main').value="";
	    $('password_check').value="";
	    $('newpassword_error').update("Ошибка: введенные пароли не содпадают");
	    $('newpassword_error_block').show();
	    return;
    }
    else
	    $('newpassword_error_block').hide();
    if($('password_main').value.length < 6 && $('password_main').value.length > 0) {
	    $('password_main').value="";
	    $('password_check').value="";
	    $('newpassword_error').update("Ошибка: пароль не может быть менее 6 символов");
	    $('newpassword_error_block').show();
	    return;
    }
    else
	    $('newpassword_error_block').hide();
    if($('offer').checked == false) {
	    $('offer_error_block').show();
	    return;
    }
    else {
	    $('offer_error_block').hide();
	    if(check_url() != 1) {
    	    if(!confirm($('site_url_input').value + " недоступен. Проверьте, нет ли ошибки в адресе сайта. Для продолжения регистрации нажмите OK.")) {
		        return;
	        }
	    }
	    $('regform').submit();
    }
}

function on_login_click() {
    $('login_field').value='';
}

function on_pass_click() {
    $('nopass_field').hide();
    $('pass_field').show();
}

function on_settotal_submit() {
    return confirm('Вы уверены что хотите удалить старую статистику и записать новые значения: hits=' + $('new_hits').value + ' hosts=' + $('new_hosts').value + ' visitors=' + $('new_visitors').value + ' sessions=' + $('new_sessions').value + '?');
}

function hotlog_nocount(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    new Ajax.Request(
        '/nocount',
        {
             method: 'get',
             parameters: { nocount: id, rand: randpar },

             onSuccess: function(oReq) {
                eval('data=' + oReq.responseText);
                if(data.status == "OK") {
                    $('nocount_link').onclick = function () { hotlog_count(id); return false; };
		            $('nocount_text').innerHTML = 'Возобновить обсчёт хитов с этого браузера.';
	                alert('Обсчёт хитов отключён');
                }
            },
            onFailure: function () { }
        }
    );
}

function hotlog_count(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    new Ajax.Request(
        '/nocount',
        {
             method: 'get',
             parameters: { count: id, rand: randpar },

             onSuccess: function(oReq) {
                eval('data=' + oReq.responseText);
                if(data.status == "OK") {
                    $("nocount_link").onclick = function () { hotlog_nocount(id); return false; };
		            $('nocount_text').innerHTML = 'Отключить обсчёт хитов с этого браузера.';
	                alert('Обсчёт хитов включён');
                }
            },
            onFailure: function () { }
        }
    );
}

function send_comment(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    new Ajax.Request(
        '/comments',
        {
             method: 'get',
             parameters: { id: id, comment: $('comment_text').value, rand: randpar },

             onSuccess: function(oReq) {
	             alert('Комментарий отправлен');
             },
             onFailure: function () { }
        }
    );    
}

function check_url() {
    var url;
    check_url_retval = 0;
    if($('site_url_input') && $('site_url_input').value) {
	    url = $('site_url_input').value;
        var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
	    new Ajax.Request(
    	    '/checkregurl',
	    {
    		method: 'get',
            parameters: { siteurl: url, rand: randpar },
		    asynchronous: false,
		    onSuccess: function(oReq) {
            	eval('data=' + oReq.responseText);
        	    if(data.status == "OK") {
			        check_url_retval = 1;
	            }
    		},
        	onFailure: function () { }
	    }
	    );
    }
    return check_url_retval;
}

function on_cat_select() {
}

function dinamika_on(im) {
    im.src = "/images/dinamika_activ.gif";
}

function dinamika_off(im) {
    im.src = "/images/dinamika.gif";
}

function active_on(el) {
    oldurl = el.src;
    regex = /.gif/;
    newurl = oldurl.replace(regex,"_active.gif");
    el.src = newurl;
}

function active_off(el) {
    oldurl = el.src;
    regex = /_active.gif/;
    newurl = oldurl.replace(regex,".gif");
    el.src = newurl;
}

function refresh_rank(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    $('google_update_button').src = '/images/refresh-progr.gif';
    new Ajax.Request(
        '/rank',
        {
             method: 'get',
             parameters: { site_id: id, action: 'newrank', rand: randpar },

             onSuccess: function(oReq) {
                eval('data=' + oReq.responseText);
                if(data.status == "OK") {
		            $('rank_update_period').update(data.period);
		            $('rank_update_msg').show();
		        }
		       else
		           alert("Невозможно обновить PR");
		       $('google_update_button').src = '/images/refresh.gif';
            },
            onFailure: function () { 
                alert('Ошибка при обновлении');
		        $('google_update_button').src = '/images/refresh.gif';
	        }
        }
    );
}

function refresh_tic(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    $('yandex_update_button').src = '/images/refresh-progr.gif';
    new Ajax.Request(
        '/rank',
        {
             method: 'get',
             parameters: { site_id: id, action: 'newtic', rand: randpar },

             onSuccess: function(oReq) {
                 eval('data=' + oReq.responseText);
                 if(data.status == "OK") {
		            $('rank_update_period').update(data.period);
    	             $('rank_update_msg').show();
		         }
		         else
		             alert("Невозможно обновить ТИЦ");
		         $('yandex_update_button').src = '/images/refresh.gif';
             },
             onFailure: function () { 
                 alert('Ошибка при обновлении');
		         $('yandex_update_button').src = '/images/refresh.gif';
	         }
        }
    );
}

function export_data() {
    if(export_menu_status) {
	    $('export_menu').hide();
	    export_menu_status = 0;
    }
    else {
	    $('export_menu').show();
	    export_menu_status = 1;
    }
}

function get_xls() {
    $('statform').action = '/getstat';
    $('getstat_format').value = 'xls';
    $('statform').submit();
}

function get_csv() {
    $('statform').action = '/getstat';
    $('getstat_format').value = 'csv';
    $('statform').submit();
}

function no_export() {
    $('statform').action = '/viewstat';
    $('statform').submit();
}

function opros(id) {
    window.open('http://hotlog.ru/opros?oid='+id, '', 'height=700, width=670, resizable=0, scrollbars=1, menubar=0,titlebar=0, location=0');
}
	
function select_counter_code() {
    if(Prototype.Browser.IE){
	    var range = document.body.createTextRange();	
	    range.moveToElementText($('counter_code_td'));
	    range.select();
    } 
    else {
	    if(Prototype.Browser.Gecko) {
	        var range = document.createRange();
	        range.selectNodeContents($('counter_code_td'));
    	    window.getSelection().removeAllRanges();
	        window.getSelection().addRange(range);
	    }
    }
}

function save_monitor(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var monitor = 1;
    if ($('monitor_value').options[$('monitor_value').selectedIndex].value == '0') {
		monitor = 0;
	}
    new Ajax.Request(
        '/editsite',
          {
             method: 'get',
             parameters: { action: 'monitor', id: id, value: monitor, rand: randpar },

             onSuccess: function(oReq) {
                 eval('data=' + oReq.responseText);
                 if(data.status == "OK") {
                    alert("Настройки сохранены.");
                 }
                 else
                     alert("Ошибка");
             },
             onFailure: function () { }
          }
     );
}

function noti_diff_period(sv) {
    if($('period'))
        if($('period').selectedIndex == 0)
            noti_period = 1;
        else 
            noti_period = 2;
    if (noti_period == 1) {
        $('diff1').removeAttribute('disabled');
        $('diff2').removeAttribute('disabled');
        $('diff3').removeAttribute('disabled');
        $('diff4').writeAttribute('disabled','disabled');
        $('diff5').writeAttribute('disabled','disabled');

        if(!$('diff_period'))
            return;
        if(sv == 2)
            $('diff_period').selectedIndex = 1;
        else
           if(sv == 1)
                $('diff_period').selectedIndex = 0;
            else
                $('diff_period').selectedIndex = 2;
	}
    else {
        $('diff4').removeAttribute('disabled');
        $('diff5').removeAttribute('disabled');
        $('diff1').writeAttribute('disabled','disabled');
        $('diff2').writeAttribute('disabled','disabled');
        $('diff3').writeAttribute('disabled','disabled');
        if(!$('diff_period'))
            return;
        if(sv == 5)
           $('diff_period').selectedIndex = 4;
        else
           $('diff_period').selectedIndex = 3;
	}
}

function noti_del(id,name) {
    if(confirm("Вы уверены что вы хотите удалить оповещение " + name + "?")) {
        location.href = "/noti/edit?id=" + id + "&action=delete";
    }
}

function hotorder_total_amount() {
    var total = 0;
    var count = 0;
    if($('gold_period') && parseInt($('gold_period').value) > 0) {
        var gold = parseInt($('gold_period').value)*prices.get('10');
        if(parseInt($('gold_period').value) >= 6) {
            if(discount_coupon == 1) {
                gold = gold - (gold * 0.4);
            }
            else {
                gold = gold - (gold * 0.1);
            }
        }
        else{
            if(parseInt($('gold_period').value) >= 3) {
                if(discount_coupon == 1) {
                    gold = gold - (gold * 0.35);
                }
                else {
                    gold = gold - (gold * 0.05);
                }
            }
            else {
                if(discount_coupon == 1) {
                    gold = gold - (gold * 0.3);
                }
            }
        }
        for(var i=0; i<$('gold_site').options.length;i++) {
            if($('gold_site').options[i].selected) {
                count++;
            }
        }
        gold *= count;
        total += gold;
    }
    if(parseInt($('silver_period').value) > 0) {
        var silver = parseInt($('silver_period').value)*prices.get('5');
        if(parseInt($('silver_period').value) >= 6) {
            if(discount_coupon == 1) {
                silver = silver - (silver * 0.4);
            }
            else {
                silver = silver - (silver * 0.1);
            }
        }
        else{
            if(parseInt($('silver_period').value) >= 3) {
                if(discount_coupon == 1) {
                    silver = silver - (silver * 0.35);
                }
                else {
                    silver = silver - (silver * 0.05);
                }
            }
            else {
                if(discount_coupon == 1) {
                    silver = silver - (silver * 0.3);
                }
            }
        }
        count = 0;
        for(var i=0; i<$('silver_site').options.length;i++) {
            if($('silver_site').options[i].selected) {
                count++;
            }
        }
        silver *= count;
        total += silver;
    }
    if(parseInt($('invisible_period').value) > 0) {
        var invisible = parseInt($('invisible_period').value)*prices.get('3');
        count = 0;
        for(var i=0; i<$('invisible_site').options.length;i++) {
            if($('invisible_site').options[i].selected) {
                count++;
            }
        }
        invisible *= count;
        total += invisible;
    }
    if(parseInt($('watcher_period').value) > 0) {
        var watcher = parseInt($('watcher_period').value)*prices.get('12');
        count = 0;
        for(var i=0; i<$('watcher_site').options.length;i++) {
            if($('watcher_site').options[i].selected) {
                count++;
            }
        }
        watcher *= count;
        total += watcher;
    }
    if(parseInt($('history_period').value) > 0) {
        var history = parseInt($('history_period').value)*prices.get('4');
        count = 0;
        for(var i=0; i<$('history_site').options.length;i++) {
            if($('history_site').options[i].selected) {
                count++;
            }
        }
        history *= count;
        total += history;
    }
    if(parseInt($('freehost_period').value) > 0) {
        var freehost = parseInt($('freehost_period').value)*prices.get('11');
        count = 0;
        for(var i=0; i<$('freehost_site').options.length;i++) {
            if($('freehost_site').options[i].selected) {
                count++;
            }
        }
        freehost *= count;
        total += freehost;
    }

    total = total - (total % 1);
    $('total_amount').innerHTML = total;
}

function check_discount() {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var discount_id = '';
    if($('discount_id')) {
        discount_id = $('discount_id').value;
    }
    else {
        return;
    }
    new Ajax.Request(
        '/hotbill', {
            method: 'get',
            parameters: { action: 'check_discount_id', discount_id: discount_id, rand: randpar },
            onSuccess: function(oReq) {
                eval('data=' + oReq.responseText);
                if(data.status == "OK") {
                    discount_coupon = 1;
                    hotorder_total_amount();    
                }
            },
            onFailure: function () {}
        }
    );
}

function create_pdf(id) {
    site_id = id;
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    new Ajax.Request(
        '/pdfstat',
        {
             method: 'get',
             parameters: { id: site_id, action: 'create_pdf', rand: randpar },

             onSuccess: function(oReq) {
                $('creating_pdf_div').show();
                $('create_pdf_button').disable();
                new PeriodicalExecuter(function(pe) {
                    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
                    new Ajax.Request(
                        '/pdfstat',
                        {
                            method: 'get',
                            parameters: { id: site_id, action: 'get_reports', rand: randpar},

                            onSuccess: function(oReq) {
                                eval('data=' + oReq.responseText);
                                if(data.status == "OK") {
                                    $('pdf_reports_table').update(data.html);
                                    $('create_pdf_div').hide();
                                    pe.stop();
                                }
                                if(data.status == "ERROR") {
                                    alert(data.msg);
                                    pe.stop();
                                }
                            },
                            onFailure: function () {}
                        }
                    );
                }, 3);
             },
             onFailure: function () { 
                 alert('Ошибка при создании заявки');
	         }
        }
    );
}

function switch_ref_selector() {
    if($('query_selector').selectedIndex != 0) {
        $('ref_selector').selectedIndex = 2;
    }
}

function switch_query_selector() {
    if($('ref_selector').selectedIndex != 2) {
        $('query_selector').selectedIndex = 0;
    }
}

function switch_country_selector() {
    if($('region_selector').selectedIndex != 0) {
        $('country_selector').selectedIndex = 1;
    }
}

function switch_region_selector() {
    if($('country_selector').selectedIndex != 1) {
        $('region_selector').selectedIndex = 0;
    }
}

