$(document).ready(function() {

	$("form.validate input").keyup(function() {
		var s=$("form.validate input").size()-1;
		var empty=s;
		
		for(var i=0; i<s; i++)
			{
				var val=$("form.validate input:eq("+i+")").val();
				if(val)
					empty--;
				else
					{
						$("form.validate p.submit span").removeClass('confirm');		
						break;
					}
			}
		
		var valTarea=$("form.validate textarea").val();
		


		if((empty==0)&&(valTarea!==''))
			$("form.validate p.submit span").addClass('confirm'); 

		if((empty==0)&&(valTarea==''))
			$("form.validate p.submit span").removeClass('confirm');
		
	 });
	
	$("form.validate textarea").keyup(function() {
		var s=$("form.validate input").size()-1;
		var empty=s;
		
		for(var i=0; i<s; i++)
			{
				var val=$("form.validate input:eq("+i+")").val();
				if(val)
					empty--;
				else
					{
						$("form.validate p.submit span").removeClass('confirm');		
						break;
					}
			}
		
		var valTarea=$("form.validate textarea").val();
		

		
		if((empty==0)&&(valTarea!==''))
			$("form.validate p.submit span").addClass('confirm');

		if((empty==0)&&(valTarea==''))
			$("form.validate p.submit span").removeClass('confirm');
		
	 });
	
    $(".makeUseIco").click(function() {
        if (!$(this).is('.activeMUI'))
        {
            $(".makeUse").toggleClass('activeMU');
            $('.helpbut').css({ display: "block" });
        }
        else
        {
            $(".makeUse").toggleClass('activeMU');
            $('.helpbut').css({ display: "none" });
            $('.helptext').css({ display: 'none' });
        }

        $(this).toggleClass('activeMUI');

        return false;
    });

    $(".makeUse").click(function() {
        if (!$(this).is('.activeMU'))
            $('.helpbut').css({ display: "block" });
        else
        {
            $('.helpbut').css({ display: "none" });
            $('.helptext').css({ display: 'none' });
        }

        $(this).toggleClass('activeMU');

        return false;
    });

//	var positions = [
//        {pos: 'right'},
//        {pos: 'left'},
//        {pos: 'center'}
//    ];

    $(".helpbut").overlay({




                    speed:100,
        //          finish:{ top: 'center', left: positions[0].pos, absolute: false },
                    finish:{ top: 'center', left: 'center', absolute: false },
                    expose: { color: '#FFF', opacity: 0.4, closeSpeed: 1000 },
                    onClose: function(){ $(".helpbut").removeClass('acthelpico'); }
                  });

    $(".helpbut").click(function() {
        if(!$(this).is('.acthelpico'))
        {
            $(this).addClass('acthelpico');

        }
    });
    
  

    $(function() {
        $(".whatIs").overlay({
            speed:100,
            finish:{ top: 10, left: 'left' }
        });
        $(".last24").overlay();
    });

    $(function() {
        $("#reyting ul li:last").addClass('last');
    });

    $("input#addToStat").keypress(function (e) {
        if (e.which == 13)
        {
            var dom = document.getElementById('addToStat').value;
            var s = $('table.comparison tr').size();
            var row = '<tr><td><input type="checkbox" id="rambler" checked="checked" /><label for="rambler">' + dom + '</label></td><td>745</td><td>435</td><td>245</td><td>425</td><td><span class="bot">54%</span></td></tr>';
            if (s < 12) $('table.comparison').append($(row));
            $("table.comparison tr:even").addClass("even");
            return false;
        }
    });

    $("input#addToStat2").click(function() {
        var dom = document.getElementById('addToStat').value;
        var s = $('table.comparison tr').size();
        var row = '<tr><td><input type="checkbox" id="rambler" /><label for="rambler">' + dom + '</label></td><td>745</td><td>435</td><td>245</td><td>425</td><td><span class="bot">54%</span></td></tr>';
        if (s < 12) $('table.comparison').append($(row));
        $("table.comparison tr:even").addClass("even");

        return false;
    });

    $("#selectReyt").click(function() {
        $("#selectReytList").fadeIn(50);
    });

    $("#popularSites").click(function() {
        $("#populatSitesList").fadeIn(50);
    });

    $("#populatSitesList li").click(function() {
        $("#populatSitesList").fadeOut(50);
        $("#populatSitesList li.active").removeClass('active');
        $(this).addClass('active');
        var text = $(this).html();
        $("#popularSites").html(text + ' <span id="selectToGraph"><img src="' + contextPath + '/images/netchart/graph-select.gif" width="9" height="5" alt="" /></span>');
    });

    $("#openCompair").click(function() {
        $(".text").removeAttr("disabled");
        $("#toCompare").slideDown('fast');
        $("div#statistic div.compare").fadeOut(50);
    });

    $("#closeCompair").click(function() {
        $("#toCompare").slideUp('fast');
        $("div#statistic div.compare").fadeIn(50);
        setTimeout(function() {
            $(".text").attr("disabled", "disabled");
        }, 500);
    });

    $("body").click(function() {
        $("#changeSiteInput").fadeOut(50);
        $("div#seeStatistic").fadeOut(50);
        $('.helptext').css({ display: 'none' });
        $('.helpbut').removeClass('helpbutactive');
    });

    $("#changeSite").click(function() {
        $("#changeSiteInput").fadeIn(50);
        $("#domen").focus();
        return false;
    });

    $("#changeSiteInput input.text").click(function() {
        $("#changeSiteInput").fadeIn(50);
        return false;
    });

    $("#changeSiteInput input.submit").click(function() {
        $("#changeSiteForm").submit();
        return false;
    });

    $("#changeSiteInput input.text").keypress(function (e) {
        if (e.which == 13)
        {
            $("#changeSiteForm").submit();
            return false;
        }
    });

    $("div.detailStatistic").click(function() {
        $("div.seeStatistic").fadeIn(50);
        $("div.seeStatistic input.text").focus();
        return false;
    });


    $("div#seeStatistic input.text").click(function() {
        $("div#seeStatistic").fadeIn(50);
        return false;
    });

    $("div#seeStatistic button").click(function() {
        $("div#seeStatistic").fadeIn(50);
    });

    $("#seeValidate").submit(function() {
        $("div#seeStatistic").fadeIn(50);
        return false;
    });


    var mininputs = 2;
    var maxinputs = 5;

    var allEnabled = $("#form5 span.enabled");
    var inpts = $(allEnabled).size();

    var allText = $("#form5 input.text");
    var size = $(allText).size();


    $("#form5 input.text").keyup(function()
    {

        // количеств заполненых
        var quantity = 0;

		// подсчет всех текстовых инпутов и проверка в цикле
        for (var i = 0; i < size; i++)
        {

            var query = "#form5 input.text:eq(" + i + ")";

            var txt = $(query).val();

            if (txt) quantity = quantity + 1;

        }

        if ((quantity < maxinputs) && (quantity >= mininputs))
        {
            var toshow = "#form5 span:eq(" + quantity + ")";
            $(toshow).addClass('enabled');
            inpts = inpts + 1;
        }

    });


    $("#closeLoadPlugin").click(function() {
        $('#loadPlugin').slideUp(50);
        setCookie('netchart_plugin', 'exists');
        return false;
    });
    $("#elseCounters").click(function() {
        window.open('inetStats!otherCountersList.html', 'elsecounters', 'width=400,height=350,resizable=no,location=no,directories=no,menubar=no,scrollbars=1');
        return false;
    });
    $("#elseSearchEngines").click(function() {
        window.open('inetStats!otherSearchEnginesList.html', 'elsesearchengines', 'width=400,height=350,resizable=no,location=no,directories=no,menubar=no,scrollbars=1');
        return false;
    });
    $("#elseActivity").click(function() {
        window.open('inetStats!otherActivityList.html', 'elseactiveity', 'width=400,height=350, resizable=no,location=no,directories=no, menubar=no,scrollbars=1')
        return false;
    });

    $("#elseCategory").click(function() {
        window.open('inetStats!otherCategoryList.html', 'elseacategory', 'width=400,height=350,resizable=no,location=no,directories=no,menubar=no,scrollbars=1')
        return false;
    });

    $("#elseAdvesory").click(function() {
        window.open('inetStats!otherAdvertList.html', 'elseadvesory', 'width=400,height=350,resizable=no,location=no,directories=no,menubar=no,scrollbars=1');
        return false;
    });

    $("#netchartTxtId").click(function() {
        $(".error").remove();
        $("#infoForm").attr("action", "webMasterSiteInfo!generateValidationFile.html").submit();
        $("#infoForm").attr("action", "webMasterSiteInfo!saveSiteInfo.html");
    });

    $("input[name='siteDescription.domainName']").keyup(function() {
        var domain = $("input[name='siteDescription.domainName']").val();
        var netchartTxtHref = $("#netchartTxtHref");
        var href;
        var aText;
        if (!domain) {
            href = "#";
            aText = "http://" + "{...}" + "/netchart.txt";
        } else {
            href = "http://" + domain + "/netchart.txt";
            aText = href;
        }
        netchartTxtHref.html(aText);
        netchartTxtHref.attr("href", href);
    });

    if (showTeaser()) {
        $('#loadPlugin').show();
    }
});

var popupStatus = 0;

function loadPopup() {
    if (popupStatus == 0) {
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        popupStatus = 1;
    }
}

function disablePopup() {
    if (popupStatus == 1) {
        $("#backgroundPopup").fadeOut("slow");
        /*	$("#elseActivityPopup").fadeOut("slow");
          $("#elseCategoryPopup").fadeOut("slow");
          $("#elseAdvesoryPopup").fadeOut("slow");*/
        popupStatus = 0;
    }
}

function updateSitesGroup(elem, groupId) {
    setCookie('netchartGroupId', groupId, 1500);
    $("#selectReytList").fadeOut(50);
    $("#selectReytList li.active").removeClass('active');
    $(elem).addClass('active');
    var text = $(elem).html();
    $("#selectReyt").html(text + ' <img src="' + contextPath + '/images/netchart/morestatistic-select.gif" alt="" width="7" height="4" />');
    var url = contextPath + "sitesGroup.html";
    var data = {groupId: groupId};
    $("#sitesGroupId").load(url, data);
}

function liFormat(row, i, num) {
    return row[0];
}

function initAutocomplete(elementId, width, left, top, url, params) {
    if (!params) {
        params = {};
    }
    if (!url) {
        url = "/autocompliteDomain.html"
    }
    params.time = new Date().getTime();
    $("#" + elementId).autocomplete(contextPath + url, {
        delay:10,
        minChars:4,
        matchSubset:1,
        autoFill:false,
        matchContains:1,
        selectFirst:false,
        formatItem:liFormat,
        maxItemsToShow:10,
        extraParams: params,
        left:left,
        top:top,
        onItemSelect: function (li) {
            if (li.extra) {
                var input = document.getElementById(elementId);
                if (!$.browser.msie) {
                    var pos = input.value.length;
                    input.setSelectionRange(pos, pos);
                }
                input.focus();
            }
        },
        width: width
    });
}

function getReferrerDomain() {
    var referrerValue = document.referrer;
    referrerValue = referrerValue.replace("http://", "");
    var firstSlashIndex = referrerValue.indexOf("/");
    var firstcolonIndex = referrerValue.indexOf(":");
    if (firstSlashIndex != -1 && firstcolonIndex != -1) {
        var substringIndex = Math.min(firstSlashIndex, firstcolonIndex);
        referrerValue = referrerValue.substring(0, substringIndex);
    } else if (firstSlashIndex != -1) {
        referrerValue = referrerValue.substring(0, firstSlashIndex);
    } else if (firstcolonIndex != -1) {
        referrerValue = referrerValue.substring(0, firstcolonIndex);
    }
    return document.domain != referrerValue ? referrerValue : "";
}

function showDisabledRating() {
    $("#sitesListId").html("<div style=\"background:url('../../images/netchart/ajax-loader.gif') 50% 20% no-repeat;height: 16px; \"></div>");
}

function showTeaser() {
    // check browser
    var showByBrowserAndPlugin = false;
    var userAgentString = navigator.userAgent;
    if (userAgentString) {
        if (userAgentString.indexOf('MSIE') != -1 || userAgentString.indexOf('Firefox') != -1) {
            if (userAgentString.indexOf('NetchartPlugin') == -1) {
                showByBrowserAndPlugin = true;
            }
        } else {
            return false;
        }
    }

    // check cookie
    var showByCookie = true;
    var netchartCookie = getCookie('netchart_plugin');
    if (netchartCookie) {
        showByCookie = false;
    }

    return showByBrowserAndPlugin && showByCookie;
}

// To use, simple do: Get_Cookie('cookie_name');
// replace cookie_name with the real cookie name, '' are required
function getCookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++)
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');

		// and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
        if (cookie_name == check_name)
        {
            b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1)
            {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
			// note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found)
    {
        return null;
    }
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function setCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());
	// if the expires variable is set, make the correct expires time, the
    // current script below will set it for x number of days, to make it
    // for hours, delete * 24, for minutes, delete * 60 * 24
    if (expires)
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
                      ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
                      ( ( path ) ? ";path=" + path : "" ) +
                      ( ( domain ) ? ";domain=" + domain : "" ) +
                      ( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function deleteCookie(name, path, domain) {
    if (getCookie(name)) document.cookie = name + "=" +
                                           ( ( path ) ? ";path=" + path : "") +
                                           ( ( domain ) ? ";domain=" + domain : "" ) +
                                           ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function roundToDigit(numberToRound, digitIndex) {
    if (numberToRound.toString().length > digitIndex) {
        var digitsNumber = numberToRound.toString().length - digitIndex;
        var result = numberToRound.toPrecision(digitIndex).replace(/\./, '').replace(/e.*/, '');
        for (var i = 0; i < digitsNumber; i++) {
            result += 0;
        }
        var amountOfDigitBeforeFirstSpace = result.length % digitIndex;
        var finalResult = '';
        if (amountOfDigitBeforeFirstSpace != 0) {
            finalResult += result.toString().substring(0, amountOfDigitBeforeFirstSpace) + ' ';
            result = result.substring(amountOfDigitBeforeFirstSpace, result.length);
        }
        var iterAmount = result.length / digitIndex;
        for (var j = 0; j <= iterAmount; j++) {
            finalResult += result.toString().substring(0, digitIndex) + ' ';
            result = result.substring(digitIndex, result.length);
        }
        return finalResult;
    }
    else {
        return numberToRound;
    }
}