var availableOn = null;
var cal = null;
var cal2 = null;
var earliestHourlyAccess = null;
var calendarCount = 0;

var Alerter = function (el) {
	el=$(el)[0];
	var close = function () {
		var delay = 400;
		//var rnd = Math.random()+'';
		//el.id='closer'+rnd.replace('0.', '');
		fadeOpacity.addRule('oR1', 1, 0, delay/10 - 10);
		fadeOpacity(el.id, 'oR1');
		setTimeout('disappear("'+el.id+'")' ,delay);

        if (window.clearData) {
            clearData(el.id);
        }
    }
	
	var appendCloser = function() {
		var button = document.createElement('img');
		if (el.className.indexOf('alert_error')!=-1) {
			button['src']="/img/alertError_closer.gif";
		}
		if (el.className.indexOf('alert_success')!=-1) {
			button['src']="/img/alertSuccess_closer.gif";
		}
		if (el.className.indexOf('alert_info')!=-1) {
			button['src']="/img/alertInfo_closer.gif";
		}                                                            
		button.className = "closer";
		el.appendChild(button);
		//button.style.left = el.getWidth()-20+"px";
		button.onclick = close;
	}
	
	appendCloser();
	
	return el;
}

function disappear (el) {
    el = $('#' + el);
    el[0].style.display="none";
    if (el.parent().parent().hasClass('infocell')) {
    	//el.up().style.border="none";
        el.parent().parent().prev().removeClass('walert_error');
        el.parent().parent().prev().removeClass('walert_success');
        el.parent().parent().prev().removeClass('walert_info');
    }

    el.parent().parent().removeClass('alert_error');
    el.parent().parent().removeClass('alert_success');
    el.parent().parent().removeClass('alert_info');

    fadeOpacity.addRule('oR1', 0, 1, 0);
    fadeOpacity(el[0].id, 'oR1');

    //if (typeof clearData == 'function') {
    //    clearData(el);
    //}
}

function switchHighlight(btn) {
        if (closer) return;

	highlight = !highlight;

	if (highlight) {
		switchButton(btn, "passive");
	} else {
		switchButton(btn, "enable");
	}
	fillTable(btn.id.substring('highlight_btn'.length), dataArray, dataContainer.timeAggregation);
	if (dataContainer.summary) fillSummary(btn.id.substring('highlight_btn'.length), dataContainer.summary);
}

function switchCloser(btn) {
       	var id = btn.id.substring('close_btn'.length);
       	highlight = false;
	if (!closer) {
        	closer = true;
       	        switchButton($('#reset_btn' + id)[0], "enable");
       	        switchButton($('#close_btn' + id)[0], "passive");
       	        switchButton($('#highlight_btn' + id)[0], "disable");
        	fillTable(id, dataArray, dataContainer.timeAggregation);
        	if (dataContainer.summary) fillSummary(id, dataContainer.summary);
	}
	else {
        	closer = false;
                closerPainted = false;
       	        switchButton($('#reset_btn' + id)[0], "disable");
       	        switchButton($('#close_btn' + id)[0], "enable");
       	        switchButton($('#highlight_btn' + id)[0], "enable");
        	fillTable(id, dataArray, dataContainer.timeAggregation);
        	if (dataContainer.summary) fillSummary(id, dataContainer.summary);
	}
}

function resetButton(btn) {
       	var id = btn.id.substring('reset_btn'.length);
       	highlight = false;
       	closer = false;
        closerPainted = false;

        switchButton($('#highlight_btn' + id)[0], "enable");
        switchButton($('#close_btn' + id)[0], "enable");
        switchButton(btn, "disable");

        resetTable(id);
        fillTable(id, dataArray, dataContainer.timeAggregation);
        if (dataContainer.summary) fillSummary(id, dataContainer.summary);
}

function switchButton(button, param) {
        if (button == null) return;

	if(param == "enable") {
		button.src = button.src.replace("_p.gif", "_e.gif");
		button.src = button.src.replace("_d.gif", "_e.gif");
	} 
	if(param == "passive") {
		button.src = button.src.replace("_e.gif", "_p.gif");
		button.src = button.src.replace("_d.gif", "_p.gif");
	}
	if(param == "disable") {
		button.src = button.src.replace("_e.gif", "_d.gif");
		button.src = button.src.replace("_p.gif", "_d.gif");
	}
}



function addDateSwitcher(parent, current) {
    $('#period1').remove();
    $('#period2').remove();
    $('#period3').remove();
    $('#period4').remove();

    switch (current) {
        case 0:
            $('#' + parent).append('<span id="period1" class="small gray" style="text-decoration: none; margin-right: 5px;">сутки</span>');
            $('#' + parent).append('<a id="period2" class="dashed small" onclick="period2(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">неделя</a>');
            $('#' + parent).append('<a id="period3" class="dashed small" onclick="period3(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">месяц</a>');
            $('#' + parent).append('<a id="period4" class="dashed small" onclick="period4(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">3 месяца</a>');
            break;
        case 1:
            $('#' + parent).append('<a id="period1" class="dashed small" onclick="period1(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">сутки</a>');
            $('#' + parent).append('<span id="period2" class="small gray" style="text-decoration: none; margin-right: 5px;">неделя</span>');
            $('#' + parent).append('<a id="period3" class="dashed small" onclick="period3(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">месяц</a>');
            $('#' + parent).append('<a id="period4" class="dashed small" onclick="period4(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">3 месяца</a>');
            break;
        case 2:
            $('#' + parent).append('<a id="period1" class="dashed small" onclick="period1(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">сутки</a>');
            $('#' + parent).append('<a id="period2" class="dashed small" onclick="period2(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">неделя</a>');
            $('#' + parent).append('<span id="period3" class="small gray" style="text-decoration: none; margin-right: 5px;">месяц</span>');
            $('#' + parent).append('<a id="period4" class="dashed small" onclick="period4(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">3 месяца</a>');
            break;
        case 3:
            $('#' + parent).append('<a id="period1" class="dashed small" onclick="period1(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">сутки</a>');
            $('#' + parent).append('<a id="period2" class="dashed small" onclick="period2(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">неделя</a>');
            $('#' + parent).append('<a id="period3" class="dashed small" onclick="period3(two);" style="text-decoration: none; margin-right: 5px;" href="javascript:void(0)">месяц</a>');
            $('#' + parent).append('<span id="period4" class="small gray" style="text-decoration: none; margin-right: 5px;">3 месяца</span>');
            break;
    }
}

function findClosestMatchingDate(checked) {
    for (var i = 1; i < availabilityArray.length; i++) {
        if (availabilityArray[i - 1].to < checked && availabilityArray[i].from > checked) return availabilityArray[i].from;
    }
    return checked;
}

function period1(two) {
    var month = '' + (currentmonth2 + 1);
    if (month.length == 1) month = '0' + month;
    var day = '' + currentday2;
    if (day.length == 1) day = '0' + day;

    $('#dateValue')[0].value = day + '/' + month + '/' + currentyear2;
    if (two) {
        $('#dateValue2')[0].value = day + '/' + month + '/' + currentyear2;
    }
    addDateSwitcher('dateSwitcher', 0);
    currentyear = currentyear2;
    currentmonth = currentmonth2;
    currentday = currentday2;

    var toHide = $('#dateValueCalendar');
    if (toHide.length > 0) toHide[0].style.display = 'none';
    //toHide = $('#dateValue');
    //if (toHide.length > 0) toHide[0].style.display = 'none';

    monthSelected();
}

function period2(two) {
    var from = new Date(currentyear2, currentmonth2, currentday2 - 7);
    var weekAgo = findClosestMatchingDate(from);
    var month = '' + (weekAgo.getMonth() + 1);
    if (month.length == 1) month = '0' + month;
    var day = '' + weekAgo.getDate();
    if (day.length == 1) day = '0' + day;

    $('#dateValue')[0].value = day + '/' + month + '/' + weekAgo.getFullYear();
    if (two) {
        month = '' + (currentmonth2 + 1);
        if (month.length == 1) month = '0' + month;
        day = '' + currentday2;
        if (day.length == 1) day = '0' + day;
        $('#dateValue2')[0].value = day + '/' + month + '/' + currentyear2;
    }
    addDateSwitcher('dateSwitcher', 1);
    currentyear = weekAgo.getFullYear();
    currentmonth = weekAgo.getMonth();
    currentday = weekAgo.getDate();

    var toShow = $('#dateValueCalendar');
    if (toShow.length > 0) toShow[0].style.display = '';
    //toShow = $('#dateValue');
    //if (toShow.length > 0) toShow[0].style.display = '';

    monthSelected();
}

function period3(two) {
    var from = new Date(currentyear2, currentmonth2 - 1, currentday2);
    var monthAgo = findClosestMatchingDate(from);

    var month = '' + (monthAgo.getMonth() + 1);
    if (month.length == 1) month = '0' + month;
    var day = '' + monthAgo.getDate();
    if (day.length == 1) day = '0' + day;

    $('#dateValue')[0].value = day + '/' + month + '/' + monthAgo.getFullYear();
    if (two) {
        month = '' + (currentmonth2 + 1);
        if (month.length == 1) month = '0' + month;
        day = '' + currentday2;
        if (day.length == 1) day = '0' + day;
        $('#dateValue2')[0].value = day + '/' + month + '/' + currentyear2;
    }
    addDateSwitcher('dateSwitcher', 2);
    currentyear = monthAgo.getFullYear();
    currentmonth = monthAgo.getMonth();
    currentday = monthAgo.getDate();

    var toShow = $('#dateValueCalendar');
    if (toShow.length > 0) toShow[0].style.display = '';
    //toShow = $('#dateValue');
    //if (toShow.length > 0) toShow[0].style.display = '';
    monthSelected();
}

function period4(two, threeMonthsAgo) {
    var from = new Date(currentyear2, currentmonth2 - 3, currentday2);
    var threeMonthsAgo = findClosestMatchingDate(from);

    var month = '' + (threeMonthsAgo.getMonth() + 1);
    if (month.length == 1) month = '0' + month;
    var day = '' + threeMonthsAgo.getDate();
    if (day.length == 1) day = '0' + day;

    $('#dateValue')[0].value = day + '/' + month + '/' + threeMonthsAgo.getFullYear();
    if (two) {
        month = '' + (currentmonth2 + 1);
        if (month.length == 1) month = '0' + month;
        day = '' + currentday2;
        if (day.length == 1) day = '0' + day;
        $('#dateValue2')[0].value = day + '/' + month + '/' + currentyear2;
    }
    addDateSwitcher('dateSwitcher', 3);
    currentyear = threeMonthsAgo.getFullYear();
    currentmonth = threeMonthsAgo.getMonth();
    currentday = threeMonthsAgo.getDate();

    var toShow = $('#dateValueCalendar');
    if (toShow.length > 0) toShow[0].style.display = '';
    //toShow = $('#dateValue');
    //if (toShow.length > 0) toShow[0].style.display = '';
    monthSelected();
}

function isCalendarDisabled(date) {
    if (availableOn == null) return false;

    var checked = new Date(date.getFullYear(), date.getMonth(), date.getDate());

    // if there's only one calendar (no range selection), then the availability is cut
    // by the earliest hourly access date (in case this report provides hourly data,
    // which is known by the non-null earliestHourlyAccess)

    // if there are two calendars, the 'to' calendar will not allow selecting an earlier date,
    // and later if it's 'from'
    var fromDate = new Date(currentyear, currentmonth, currentday);
    var toDate = new Date(currentyear2, currentmonth2, currentday2);
    for (var range in availableOn) {
        if (earliestHourlyAccess != null && this.dateElement == 'dateValue') {
            if (checked.getTime() < earliestHourlyAccess.getTime()) {
                return true;
            }
        }
        if (this.dateElement == 'dateValue2' && fromDate.getTime() != toDate.getTime()) {
            // not earlier than current date #1
            if (checked.getTime() < fromDate.getTime()) return true;
        }
        if (this.dateElement == 'dateValue' && fromDate.getTime() != toDate.getTime()) {
            // not later than current date #2
            if (checked.getTime() > toDate.getTime()) return true;
        }
        if (availableOn[range].from.getTime() <= checked.getTime() && availableOn[range].to.getTime() >= checked.getTime()) return false;
    }
    return true;
}

function onCalendarSelected(_cal, date) {
    if (_cal.dateClicked) {
        var currentMode = $('span#period1');
        var currentMode2 = $('a#period1');
        if (currentMode.length > 0 || (currentMode.length == 0 && currentMode2.length == 0)) {
            // single calendar, both from and to are selected
            currentyear2 = parseInt(date.substring(6, 10));
            currentmonth2 = date.substring(3, 5);
            if (currentmonth2.substring(0, 1) == '0') currentmonth2 = currentmonth2.substring(1);
            currentmonth2 = parseInt(currentmonth2) - 1;
            currentday2 = date.substring(0, 2);
            if (currentday2.substring(0, 1) == '0') currentday2 = currentday2.substring(1);
            currentday2 = parseInt(currentday2);

            currentyear = currentyear2;
            currentmonth = currentmonth2;
            currentday = currentday2;
            $('#dateValue')[0].value = date;

        }
        else {
            if (_cal.dateElement == 'dateValue2') {
                currentyear2 = parseInt(date.substring(6, 10));
                currentmonth2 = date.substring(3, 5);
                if (currentmonth2.substring(0, 1) == '0') currentmonth2 = currentmonth2.substring(1);
                currentmonth2 = parseInt(currentmonth2) - 1;
                currentday2 = date.substring(0, 2);
                if (currentday2.substring(0, 1) == '0') currentday2 = currentday2.substring(1);
                currentday2 = parseInt(currentday2);
            }
            else {
                currentyear = parseInt(date.substring(6, 10));
                currentmonth = date.substring(3, 5);
                if (currentmonth.substring(0, 1) == '0') currentmonth = currentmonth.substring(1);
                currentmonth = parseInt(currentmonth) - 1;
                currentday = date.substring(0, 2);
                if (currentday.substring(0, 1) == '0') currentday = currentday.substring(1);
                currentday = parseInt(currentday);
            }
        }
        $('#aggregationSubmit')[0].disabled = false;


        calendarCount--;
        _cal.hide();
        $('#' + _cal.dateElement)[0].value = date;
        if (_cal.dateElement == 'dateValue2') cal2 = null;
        else cal = null;

        // check if the date is very early
        //var dateObj = new Date(currentyear, currentmonth, currentday);
        //alert(earliestHourlyAccess + ":" + dateObj.getTime() + ' - ' + earliestHourlyAccess.getTime() + ' = ' + (dateObj.getTime() - earliestHourlyAccess.getTime()));
        //updateData();
    }
}

function initCalendar(parentElement, available, dateElement, selected) {
    if ('dateValue2' == dateElement) {
        if (cal2 != null && cal2.dateElement == dateElement) {
            cal2.hide();
            cal2 = null;
            return;
        }
        else {
            if (cal != null) {
                cal.hide();
                cal = null;
            }
        }
    }
    else {
        if (cal != null && cal.dateElement == dateElement) {
            cal.hide();
            cal = null;
            return;
        }
        else {
            if (cal2 != null) {
                cal2.hide();
                cal2 = null;
            }
        }
    }

    calendarCount++;

    var parent = $("#" + parentElement)[0];
    availableOn = available;

    //var firstDate = selected;

    var firstDate = 'dateValue2' == dateElement ? new Date(currentyear2, currentmonth2, currentday2) : new Date(currentyear, currentmonth, currentday);

    //if (firstDate == null && availableOn != null && availableOn.length > 0) {
    //    firstDate = availableOn[availableOn.length - 1].to;
    //}
    //if (firstDate == null) {
    //    firstDate = new Date();
    //}

    // date is cloned to avoid in-place modification
    var calen = new Calendar(1, firstDate.toDateString(), onCalendarSelected);

    calen.dateElement = dateElement;
    calen.weekNumbers = false;
    calen.withTooltip = false;
    calen.setDisabledHandler(isCalendarDisabled);
    calen.setDateFormat("%d/%m/%Y");
    if (availableOn != null) calen.setRange(availableOn[0].from.getFullYear(), availableOn[availableOn.length - 1].to.getFullYear());
    calen.create();
    calen.showAtElement(parent, "Br");

    if (dateElement == 'dateValue2') cal2 = calen;
    else cal = calen;
}


function switchmenu() {
    this.opened = true;

    if (this.pp != null) {

        this.parentsParent = this.pp;
        this.subs = this.parentsParent.getElementsByTagName("DD");

        this.hideSubs = function () {
            this.parentsParent.className += " closed";
            this.opened = false;
        };

        this.showSubs = function () {
            this.parentsParent.className = this.parentsParent.className.replace(" closed", "");
            this.opened = true;
        };

        if(!this.bheight){
            this.parentsParent.className += " closed";
            this.bheight=parseInt(this.parentsParent.clientHeight);
        }

        if(!this.sheight){
            this.parentsParent.className=this.parentsParent.className.replace(" closed", "");
            this.sheight=parseInt(this.parentsParent.clientHeight);
        }

        if (this.parentsParent.className.indexOf('closed') == -1) { this.hideSubs(); } else { this.showSubs(); };
        return false;
    }
    else {
        return true;
    }
	
}

function clickReportDescriptionHandler() {
    clickHandler('report_descr_link', 'report_description', 'report_example_link', 'report_example');
}

function clickReportExampleHandler() {
    clickHandler('report_example_link', 'report_example', 'report_descr_link', 'report_description');
}

function clickHandler(id, textId, secondId, secondTextId) {
    var el = $('#' + id)[0];
    var textEl = $('#' + textId);
    if (el.className == 'clicked_link') {
        el.className = 'unclicked_link';
        textEl[0].style.display = 'none';
        textEl.parent()[0].style.display = 'none';
    }
    else {
        var secondEl = $('#' + secondId)[0];
        var secondTextEl = $(secondTextId)[0];
        if (secondEl && secondEl.className == 'clicked_link') {
            secondEl.className = 'unclicked_link';
            secondTextEl.style.display = 'none';
        }
        el.className = 'clicked_link';
        textEl.parent()[0].style.display = 'block';
        textEl[0].style.display = 'inline';
    }
}

var toggleChart = function (el) {
	this.parent = $(el);
	//alert(el);
	//var bhead = this.parent.children('.bhead');
	var bhead = this.parent.children('.bhead');
	//alert('bhead:' + bhead);
	var buttonCont = bhead.children('.co');
	//var closingEl = this.parent.children('.closing')[0].id;
	//alert('looki:' + this.parent.children('.closing')[0]);
	var closingEl = this.parent.children('.closing')[0].id;
	this.parent.children('.closing')[0].style.position = "relative";
	var closingEl2 = $('#' + closingEl).children()[1].id;

	var closed = false;

	var setIcon = function(type) {
            if (buttonCont) {
                if (type == "plus") {
                    buttonCont.children().removeClass("minus");
                    buttonCont.children().addClass("plus");
                } else {
                    buttonCont.children().removeClass("plus");
                    buttonCont.children().addClass("minus");
                }
            }
        }

	if (closed) {
		closingEl.hide();
		//closingEl.style.height = "1px";
		//if (closingEl.id.startsWith('table')) {
                //    closingEl.style.overflow = "hidden";
		//}
		setIcon("plus");
	} else {
		setIcon("minus");
	}

	var open = function () {
	        var beingClosed = $('#' + closingEl);
	        //var beingClosed = closingEl;
       		//beingClosed.show();
		setIcon("minus");
		if (buttonCont.length > 0) buttonCont[0].onclick = close;

	        var chart = beingClosed[0].id.substr(0, 8) == 'subchart' || beingClosed[0].id.substr(0, 12) == 'subDoublePie';

		if ($.browser.msie) {
         		if (!chart) {
         			beingClosed.show();
         		}
         		else {
         			beingClosed[0].style.overflow = "visible";
         			beingClosed[0].style.visibility = "visible";
         			beingClosed[0].style.height = "510px";
         		}
		}
		else {
         		if (!chart) {
         			beingClosed.show();
         		}
         		else {
         			//beingClosed.show();
         			//$('#chart0')[0].style.visibility = "visible";
         			//$('#chart0')[0].style.height = "480px";
         			beingClosed[0].style.visibility = "visible";
         			//beingClosed[0].style.overflow = "visible";
         			beingClosed[0].style.height = "510px";
                		$('#' + closingEl2)[0].style.visibility = "visible";
         		}
         	}
		return false;
	}

    var close = function () {
        var beingClosed = $('#' + closingEl);
        var chart = beingClosed[0].id.substr(0, 8) == 'subchart' || beingClosed[0].id.substr(0, 12) == 'subDoublePie';

        //beingClosed.hide();
        setIcon("plus");
        if (buttonCont.length > 0) buttonCont[0].onclick = open;
        if ($.browser.msie) {
            if (chart) {
                beingClosed[0].style.visibility = "hidden";
                beingClosed[0].style.overflow = "hidden";
                beingClosed[0].style.height = "1px";
            }
            else {
                beingClosed.hide();
            }
        }
        else {
            if (!chart) {
                beingClosed.hide();
            }
            else {
                //beingClosed.hide();
                //$('#chart0')[0].style.visibility = "hidden";
                //$('#chart0')[0].style.height = "1px";
                beingClosed[0].style.visibility = "hidden";
                //beingClosed[0].style.overflow = "hidden";
                beingClosed[0].style.height = "1px";
                $('#' + closingEl2)[0].style.visibility = "hidden";
            }
        }
      	return false;
    }

    if (buttonCont.length > 0) buttonCont[0].onclick = close;
}

function appendMenuElements() {
    $('#mainmenu dl.ex a').click(switchmenu);
    $('#mainmenu dl.ex dt a').each(function() {
        $(this)[0].href = 'javascript:void(0)';
        $(this)[0].pp = $(this).parent().parent()[0];
    });
}

function switchReportEmailHelp(subscribe) {
    if (subscribe) $('#report_emailing_description_dont').toggle(); 
    else $('#report_emailing_description_do').toggle();
}

function isFloat(arg) {
        if (arg == null) return false;

        var ind1 = new String(arg).indexOf('.');
        var ind2 = new String(arg).lastIndexOf('.');

        if (ind1 != ind2) return false;

	var f = parseFloat(arg);
	if (f != f) {
		return false;
        }
	return parseInt(arg) != f;
}

function sendValue(id, index) {
    //alert($('#' + id)[0].innerHTML);
    //$('#value_input' + index)[0].value = $('#' + id)[0].innerHTML;
    $('#value_input' + index)[0].value = id;
}


function doExport(form, format, num) {
    $('#format' + num)[0].value = format;
    $('#geoAggregationValue' + num)[0].value = $('#geoAggregationValue')[0].value;
    $('#dateValue' + num)[0].value = $('#dateValue')[0].value;
    if ($('#dateValue2').length > 0) {
        $('#dateValue2' + num)[0].value = $('#dateValue2')[0].value;
    }
    if ($('#hour').length > 0) {
        $('#hour' + num)[0].value = $('#hour')[0].value;
    }

    //alert(form);
    form.submit();
}


$(document).ready(function() {
    appendMenuElements();

    var slideEls = $('.slide');
    if (slideEls.length) {
    	for (var i = 0; i < slideEls.length; i++) {
    	    new toggleChart(slideEls[i]);
    	}
    }

    var alertEls = $('.alert');
    if (alertEls.length) {
    	for (var i = 0;i < alertEls.length; i++) {
    	    var oo = new Alerter(alertEls[i]);
    	}
    }
});

