function isDomainsChecked()
{
	for (i in checkTLD)
    { 
        ename = checkTLD[ i ].replace(/\./g, "_");
        if($("#check_" + ename).is(':checked'))
        {
            return true;
        }
	}
	return false;
}

function showHideOrderButton()
{
    disabledButtonClassName = "disabledButton";
    orderButtonSelector = ".orderButton";
    orderButton = $(orderButtonSelector);
    if (orderButton.length == 0) return;
    
    if(isDomainsChecked())
    {
        orderButton.each(
            function(i, val) {
                val = $(val);
                if(val.hasClass(disabledButtonClassName)) {
                    val.removeClass(disabledButtonClassName)
                }
                val.bind("click", 
                    function(e) {
                        $(this).unbind("click");
                        $("#formCheckDomains").submit();
                        
                        // Hack to fix IE6 strange behavior
                        if(jQuery.browser.msie == true && jQuery.browser.version < 7)
                        {
                            return false;
                        }
                        
                        return true;
                    }
                );
            }
        );
	} 
    else 
    {
        orderButton.each(
            function(i, val) {
                val = $(val);
                if(!val.hasClass(disabledButtonClassName))
                {
                    val.addClass(disabledButtonClassName);
                }
                val.unbind("click");
            }
        );
        
	}
}

function activateCheckBox(id)
{
	$("#" + id).attr('checked', true);
}

function deactivateCheckBox(id)
{
	$("#" + id).attr('checked', false);
}

function toggleCheckBox(id)
{
    el = $("#" + id);
    el.attr('checked', !el.is(':checked'));
}

function checkDomain(sld, tld)
{
    var domain = sld +'.'+ tld;
    var url = "/domain/das/" + domain + "/";
    var request = $.ajax({
        url: url,
        type: 'POST',
        /*contentType: 'application/x-www-form-urlencoded; charset=ISO-8859-1',*/
        success: function(msg) {
            requestEnd(domain);
            if (msg == null || msg == "") {
                reply = new Object();
                reply.available = 2;
            }
            else {
                reply = eval('(' + msg + ')');
            }

            updateDomainStatus(reply.domain, sld, tld, reply.available);
            ++checkI;
        },
        error: function(XMLHttpRequest, textStatus) {
            //updateDomainStatus(domain, sld, tld, '2');
            requestEnd(domain);
        }
    });
    requestStart(sld +'.'+ tld, request);
}

var ajaxRequests = [];
function abort()
{
    for (var id in ajaxRequests)
    {
        var request = ajaxRequests[id];
        requestEnd(id);
    
        if (request != null)
        {
            var ld_data = id.split(".", 2);
            var sld = ld_data[0];
            var tld = ld_data[1];
            updateDomainStatus(id, sld, tld, '3');
        }
    }
    return true;
}

function requestEnd(id)
{
    var request = ajaxRequests[id];
    ajaxRequests[id] = null;
    ajaxRequests.splice(id, 1);
    if (request != null)
    {
        try { request.abort() } catch (err) { }
    }
}

function requestStart(id, request)
{
    ajaxRequests[id] = request;
}

function updateDomainStatus(domain, sld, tld, status)
{
    ename = tld.replace(/\./g, "_");
    if( $("#tld_" + ename + '_1').length == 0 ) return true;

    domain = sld + "." + tld;
    var statusText = "Fejl";
    var statusIcon = "Retry";
    
    // errornous
    if (status == null || status.toString() == '2')
    {
        statusText = "Fejl";
        statusIcon = "Retry";
        //statusTd.html('<a href="javascript:retry(\'' + sld + '\', \'' + tld + '\')" title="Opslaget fejlede, klik her for at prøve igen"><img src="/images/icons/refresh.png" alt="" /></a> Fejl');
        //return;
    }
    else if (status.toString() == '3')
    {
        statusText = "Afbrudt";
        statusIcon = "Retry";
        //statusTd.html('<a href="javascript:retry(\'' + sld + '\', \'' + tld + '\')" title="Opslaget blev afbrudt, klik her for at prøve igen"><img src="/images/icons/refresh.png" alt="" /></a> Afbrudt');
        //return;
    }
    else
    {
        // set price pr. year
        priceTd = $("#tld_" + ename + '_4');
        $("#tld_" + ename + '_5').text(prices[tld]['prisaar']);
        
        // whois td
        whoisTd = $("#tld_" + ename + "_" + 3);
        
        // set click events on each cell
        for(i = 1; i <= 5; i++) {
            var e = $("#tld_" + ename + "_" + i);
            e.unbind("click");
            e.bind
            (
                "click", 
                {"tld": tld},
                function(e){
                    elCheckbox = $("#check_" + e.data.tld);
                    elCheckbox.attr(
                        "checked", 
                        !elCheckbox.attr("checked")
                    );
                    showHideOrderButton();
                }
            );
        }
        
        $("#check" + ename).unbind("click");
        $("#check" + ename).bind
        (
            "click", 
            {"tld": tld},
            function(e){
                elCheckbox = $("#check_" + e.data.tld);
                elCheckbox.attr(
                    "checked", 
                    !elCheckbox.attr("checked")
                );
                showHideOrderButton();
            }
        );

        switch(status.toString()) 
        {
            case '1':
                // available
                
                // set status text
                statusText = 'Ledigt';
                statusIcon = 'Ok';
                
                // set price text
                priceTd.text(prices[tld]['prisopret']);
                break;

            case '0':
                // occupied
                
                // set status text
                statusText = 'Optaget';
                statusIcon = '';
                
                // set price text
                priceTd.text(prices[tld]['prisflyt']);
                
                // unbind whois cell
                whoisTd.unbind("click");
                
                // add new whois binding
                whoisTd.bind(
                    "click",
                    function(e)
                    {
                        container = $('#whoisContainer');
                        container.dialog('option', 'title', 'Henter Whois data for ' + domain);
                        
                        var url = '/domain/whois/' + domain + '/';
                        var request = $.ajax({
                           url: url,
                           cache: false,
                           success: function(msg) {
                             data = eval('(' + msg + ')');
                             $('#whoisData').html('<pre>' + data.whois + '</pre>');
                             container.dialog('option', 'title', 'Whois ' + domain);
                           },
                           error: function (XMLHttpRequest, textStatus) {
                             $('#whoisData').html('<pre>' + XMLHttpRequest.responseText + '</pre>');
                             container.dialog('option', 'title', 'Whois fejl for ' + domain);
                           }
                        });
                        ajaxRequests[ajaxRequests.length-1] = request;
                        
                        container.dialog('open');
                    }
                );
                $("#tld_" + ename + "_3 img").show();
                break;

            default:
                return;
	    }
    }

    $("#tld_" + ename + '_2 .domainSearchBusyTextContainer').text(statusText);
    $("#tld_" + ename + '_2 .domainSearchBusyGraphicsContainer img').hide();
    $("#tld_" + ename + '_2 .domainSearchBusyGraphicsContainer img[alt='+statusIcon+']').show();

    // generate checkBoxId
    checkBoxId = 'check_' + ename;
    checkBoxTd = $("#tld_" + ename + '_0');

    checkBoxTd.html('<input type="checkbox" id="' + checkBoxId + '" name="tlds[]" value="' + tld + '" />');
    checkBox = $('#' + checkBoxId);
    checkBox.bind( "change", showHideOrderButton );
	
    /*
	if(jQuery.inArray(tld, checkedTLDS))
    {
		activateCheckBox(checkBoxId);
        checkBox.trigger("change");
		//showHideOrderButton();
	}
    */
	
	return true;
}

function retry(sld, tld)
{
    $("#tld_" + tld + '_2 .domainSearchBusyGraphicsContainer img').hide();
    $("#tld_" + tld + '_2 .domainSearchBusyGraphicsContainer img[alt=Busy]').show();
	//$("#tld_" + tld + '_2 .domainSearchBusyGraphicsContainer').html('<img src="/images/icons/busy.gif" alt="" />');
    $("#tld_" + tld + '_2 .domainSearchBusyTextContainer').html('S&oslash;ger...');

    checkDomain(sld, tld);
}

function check_all_domains()
{
    for(i = 0; i <= checkTLD.length; i++)
    {
        id = "check_" + checkTLD[i];
        if($("#" + id))
        {

        }
	    activateCheckBox( id );
    }
    showHideOrderButton();
}

/** domain actions **/

function underscoreDomain(domain)
{
    return domain.replace('.', '_');
}

function changeProduct(domain, productType)
{
    if(productType == "domain") return;
    uncheckAllProductTypes(productType);
    checkDomainProductType(domain, productType);
}

function checkDomainProductType(domain, productType)
{
    $("#" + productType + "_" + underscoreDomain(domain)).attr("checked", true);
}

function uncheckDomainProductType(domain, productType)
{
    $("#" + productType + "_" + underscoreDomain(domain)).attr("checked", false);
    checkDomainProductType(domain, "domain");
}

function uncheckAllProductTypes(productType)
{
    for (i=0;i<domains.length;i++)
    {
	domain = domains[i];
        element = $("#" + productType + "_" + underscoreDomain(domain));
        // element = $("#" + productType + "_" + domain);
        if(element.is(':checked'))
        {
            uncheckDomainProductType(domain, productType);
        }
    }
}

function checkProductByClass(objCheckbox, productClass)
{
    jQuery.each(
        $('.' + productClass),
        function()
        {
            $(this).attr('checked', false);
        }
    ); 
    $(objCheckbox).attr('checked', true);
}

$(function() {
    if ($('#whoisContainer').length > 0)
    {
        $('#whoisContainer').dialog(
            {
                resizable: true,
                modal: true,
                draggable: true,
                autoOpen: false,
                title: 'Whois',
                width: 600,
                height: 400,
                buttons: { "Ok": function() { $(this).dialog("close"); } },
                open: function(event, ui) 
                {
                    $("#whoisData").text("Henter data...");
                }
            }
        )
    }
});