function ChangeImg() {
	if(document.images) { eval("document."+ChangeImg.arguments[0]+".src=('"+ChangeImg.arguments[1]+"')");}
}
function preload() {
	if (document.images) {
		a = document.body.clientWidth;
		var imgsrc = preload.arguments;
		arr=new Array(imgsrc.length);
		for (var j=0; j<imgsrc.length; j++) {arr[j]=new Image; arr[j].src=imgsrc[j];}
	}
}

function getCookie(name) {
        var prefix = name + "="
        var cookieStartIndex = document.cookie.indexOf(prefix)
        if (cookieStartIndex == -1)
                return null
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}

function setCookie(name, value, expires, path, domain, secure) {
        document.cookie = name + "=" + escape(value) +
                                                ((expires) ? "; expires=" + expires : "") +
                                                ((path) ? "; path=" + path : "") +
                                                ((domain) ? "; domain=" + domain : "") +
                                                ((secure) ? "; secure" : "");
}


function sfLoading() {
	$('listContent').innerHTML = '<div style="width:100%;height:100%;"><br /><br /><br /><br /><center><img src=/images/indicator-small.gif>&nbsp;Загрузка...</center></div>';
	$('cont_new_saveall_btn').disable();
}

function CheckType(field, nfield) {
    var new_field = document.getElementById(nfield);
	var new_field_tr = document.getElementById(nfield + '1');
	if(field[field.selectedIndex].value == -1) {
		new_field.disabled = false;
		new_field.className = new_field.className.replace(' disabled_txt','');
		new_field_tr.className = 'enabled_tr';
	} else {
		new_field.disabled = true;
		new_field.className = new_field.className.replace(' disabled_txt','');
		new_field.className += ' disabled_txt';
		new_field_tr.className = 'disabled_tr';
	}
}

function checkTopics(nfield) {
    var b = 1;
    for (var i = 0;i<$j('#add_topicId').val().length;i++) {
        if ($j('#add_topicId').val()[i] == -1) {
            $j('#'+nfield).attr('disabled', false);
            $j('#'+nfield).removeClass('disabled_txt');
            $j('#'+nfield+'1').addClass('enabled_tr');
            $j('#'+nfield+'1').removeClass('disabled_tr');
            b = 2;
        }
    }

    if (b == 1) {
        $j('#'+nfield).attr('disabled', true);
        $j('#'+nfield).addClass('disabled_txt');
        $j('#'+nfield+'1').addClass('disabled_tr');
        $j('#'+nfield+'1').removeClass('enabled_tr');
    }
}

function updateSelectJSON(request, json, element)
{
	if (element.length != 0) {
		element.options.length = 0;
	}

	json.each(function (item){
		element.options[element.options.length] = new Option(item.text, item.value);
	});
}

function captchaRefresh(url)
{
	url += '?hashCode='+Math.random(999);
    document.getElementById('captchaId').src=url;
}

function setDaysByMonth(id, monthId)
{
//	var days = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var days = new Array(31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31);
	var selectBoxId = id+"Days";
	var defaultValue = document.getElementById(selectBoxId).value;
//alert($(selectBoxId).options.length);
//    if ($(selectBoxId).options.length > 0) {
//        for (var i=$(selectBoxId).options.length;i>0;i--) {
//            $(selectBoxId).options[i-1].remove();
//        }
//    }
	for (i=1;i<=days[monthId];i++) {
		document.getElementById(selectBoxId).options[document.getElementById(selectBoxId).options.length] = new Option(i, i);
		if (i == defaultValue) {
    		document.getElementById(selectBoxId).options[document.getElementById(selectBoxId).options.length-1].selected = true;
		}
    }
    insertCurrentSelectedDate(id);
}

function initYears()
{
	var currentDate = new Date();
	for (var i=currentDate.getYear()-3;i<=currentDate.getYear()+2;i++) {
		if (i<1000) a = 1900 + i; else a = i;
    	document.getElementById("startYears").options[document.getElementById("startYears").options.length]             = new Option(a, a);
    	document.getElementById("endYears").options[document.getElementById("endYears").options.length] 		        = new Option(a, a);
    	document.getElementById("lastRequestYears").options[document.getElementById("lastRequestYears").options.length] = new Option(a, a);
    }
}

function initYear(id)
{
	var currentDate = new Date();
	for (var i=currentDate.getYear()-80;i<=currentDate.getYear()-10;i++) {
		if (i<1000) a = 1900 + i; else a = i;
    	$(id+"Years").options[$(id+"Years").options.length]	= new Option(a, a);
    }
}

function initSelectBoxes() {
	var currentDate = new Date();
	setDaysByMonth("start", currentDate.getMonth());
	setDaysByMonth("end", currentDate.getMonth());
	setDaysByMonth("lastRequest", currentDate.getMonth());
	$("startMonths").options[currentDate.getMonth()].selected = true;
	$("endMonths").options[currentDate.getMonth()].selected = true;
	$("lastRequestMonths").options[currentDate.getMonth()].selected = true;
	initYears();
	insertCurrentSelectedDate('start');
	insertCurrentSelectedDate('end');
	insertCurrentSelectedDate('lastRequest');
}

function insertCurrentSelectedDate(parent)
{
	var m = $(parent+"Months").getValue();
	var d = $(parent+"Days").getValue();
	var y = $(parent+"Years").getValue();
	
	if (m.toString().length == 1) m = "0"+m;
	if (d.toString().length == 1) d = "0"+d;
	
	$(parent+"Date").value = y+"-"+m+"-"+d;
}

function initSearchSelectBoxes() {
	var currentDate = new Date();
//	setDaysByMonth("startSearch", currentDate.getMonth());
//	setDaysByMonth("endSearch", currentDate.getMonth());
	$("startSearchMonths").options[currentDate.getMonth()].selected = true;
	$("endSearchMonths").options[currentDate.getMonth()].selected = true;
	initSearchYears();
	insertCurrentSelectedDate('startSearch');
	insertCurrentSelectedDate('endSearch');
}

function initSearchYears()
{
	var currentDate = new Date();
	for (var i=currentDate.getYear()-3;i<=currentDate.getYear()+3;i++) {
		if (i<1000) a = 1900 + i; else a = i;
    	$("startSearchYears").options[$("startSearchYears").options.length] 	= new Option(a, a);
    	$("endSearchYears").options[$("endSearchYears").options.length] 		= new Option(a, a);
    }
}

function initSelectBox(id) {
	var currentDate = new Date();
	setDaysByMonth(id, currentDate.getMonth());
	$(id+"Months").options[currentDate.getMonth()].selected = true;
	initYear(id);
	insertCurrentSelectedDate(id);
}

function checkKeywords()
{
	if ($('search_keywords').value == 'Найти') {
		$('search_keywords').value = '';
	}
	return true;
}

function initSelect(id, val)
{
    if (val == "") 
        return;
        
    var value = 0;
    
    for (var i=0;i<$(id).options.length;i++) {
        value = $(id).options[i].value;

        if (value < 10) {
            value = "0"+value;
            $(id).options[i].value = value;
        }
    
        if (value == val) {
            $(id).options[i].selected = true;
        }
    }
}

function initInput(id, val)
{
	if (val == "") return;
	if ($(id)) {
		$(id).value = val;
	}
}

function checkit()
{
    if ($('#add_domain').getValue() == '') {
        alert('Введите домен');
        return false;
    }
    if ($('#add_width').getValue() == '') {
        alert('Установите ширину');
        return false;
    }
    
    if ($('#add_limit').getValue() == '') {
        alert('Установите количество объявлений');
        return false;
    }
    
    if ($('#add_titleSize').getValue() == '') {
        alert('Установите размер шрифта названия мероприятия');
        return false;
    }
    
    if ($('#add_textSize').getValue() == '') {
        alert('Установите размер шрифта текста объявления');
        return false;
    }
    return true;
}

function getPrivateKey(request, json)
{
    if (request.responseText != '') {
        $('informerCode').value = request.responseText;
        $('informerSource').show();
    }
}

function doLink(makeUrl, id)
{
    new Ajax.Updater('main_td', makeUrl, {asynchronous:true, evalScripts:true, onLoading:function(request, json){$('main_td').innerHTML='<br /><br /><br /><br /><center>Загрузка <img src="/images/indicator-small.gif" /></center>';}});; 
    
    $('menu_1').className = '';
    $('menu_2').className = '';
    $('menu_3').className = '';
    $('menu_4').className = '';
    $('menu_5').className = '';
    
    if (id) {
        $(id).className = 'act';
    }
    return false;
}

function goToTopic(object, makeUrl)
{
    document.getElementsByClassName('myTopicClassName').each(function (item){
		item.setStyle({ 'font-weight': 'normal' });
	});
    new Ajax.Updater('main_td', makeUrl, {asynchronous:true, evalScripts:false, onLoading:function(request, json){$('main_td').innerHTML='<br /><br /><br /><br /><center>Загрузка <img src="/images/indicator-small.gif" /></center>';}});; 
    object.setStyle({ 'font-weight': 'bold' });
    return false;
}

function checkParticals(obj)
{
    if ($(obj).getValue() == -1) {
       $('titles').hide();
    } else {
       $('titles').show();
    }
}

function switchValue(objectId) {
    if ($('m_'+objectId).src.indexOf('down.png') > -1) {
        ChangeImg('m'+objectId,'/images/up.png');
    } else {
        ChangeImg('m'+objectId,'/images/down.png');
    }
}

function switchRequests(object)
{
    if (object.innerHTML == '[Раскрыть все]') {
        document.getElementsByClassName('requestsItem').each(function (item){
        
            new Effect.SlideDown(item.getAttribute('id'));
            switchValue(item.getAttribute('id'));
            
    	});
    	
    	object.innerHTML = '[Свернуть все]';
    } else {
        document.getElementsByClassName('requestsItem').each(function (item){
        
            new Effect.SlideUp(item.getAttribute('id'));
            switchValue(item.getAttribute('id'));
            
    	});
    	
    	object.innerHTML = '[Раскрыть все]';
    }
}

function showIndicator(objectId) {
    $(objectId).innerHTML = "Идет отправка формы <img src='/images/indicator-small.gif' />";
}

function mouseMove(el) {
	$j(el).addClass('marked');
}

function mouseOut(el) {
	$j(el).removeClass('marked');
}

var Objects = {};
function doIt(objectId) {
    if (Objects[objectId] != 1) {
        new Effect.toggle('request'+objectId, 'slide', {});
        switchValue('request'+objectId);
    }
}

function changeDate(obj, id)
{
    var arr = obj.value.split('-');
    if (arr[2] && arr[1] && arr[0]) {
        $(id).value = arr[2]+'-'+arr[1]+'-'+arr[0];
    } else {
        $(id).value = '';
    }
}

function checkAll(obj, fName)
{
    var a = $('checks').getElementsByClassName('checkbox_for_delete');
    for (var i = 0; i< a.length; i++ ) {
        a[i].checked = obj.checked;
    }
    obj.disabled = false;
}

function block(objectId) {
    Objects[objectId] = 1;
}
function unblock(objectId) {
    Objects[objectId] = -1;
}

function deleteSelected(formId, url) {
    location.href=url+'&'+$(formId).serialize();
}



function add(title) {
    insertAtCursor($('messageTemplate'), title);
}

function insertAtCursor(myField, myValue) {
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    } else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

function removeItem(url, item) {
    if (confirm('Вы уверены что хотите удалить элемент? Операция не обратима.')) {
        prepareAjax(url, "GET");
        _ajax(url);
        $j('.item-'+item).remove();
    }
    return false;
}
