function renewCheckedProducts() 
{
    var products = new Array();

    document.getElementById("LoadingDiv").style.display = 'block';

    for(var i = 0; ;i++)
    {
	if(document.getElementById("product_"+i))
	{
	    if(document.getElementById("product_"+i).checked)
	        products.push(document.getElementById("product_"+i).value);
	}
	else
	{
	    break;
	}
    }
    postURL('/products-pricing/services/productCart.php', 'action=loadproductrenewals&names='+encodeURIComponent($.toJSON(products)), renewCheckedProductsHandler);
}

function renewCheckedProductsHandler(status, content, contentType) 
{
    resetLoadingDiv();

    if(status != 200 && status != 0)
    {
        alert("Something went wrong. Please refresh the page and try again. ("+status+")");
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        alert(results["message"]);
        return;
    }

    window.location = "/checkout.php";
}

function updateProductRecurringBilling(value, domainName, type) 
{
    document.getElementById("LoadingDiv").style.display = 'block';
    getURL('/products-pricing/services/productCart.php?action=updateproductrecurringbilling&value='+value+'&name='+domainName+'&type='+type, updateProductRecurringBillingHandler);
}

function updateProductRecurringBillingHandler(status, content, contentType) {
    resetLoadingDiv();

    if(status != 200 && status != 0)
    {
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        return;
    }

    var message = "";
    if(results["value"] == 1)
    {
	message = "Automatic Billing has been turned on for this product.";
	if(!results["hasDefaultPaymentProfile"]) message += "\n\nAutomatic Billing will not function without a default billing profile. You will now be taken to a page that allows you to create one.";
	alert(message);
	if(!results["hasDefaultPaymentProfile"])
	{
	    window.location = "/management/payment-profiles.php#creditCardForm";
	    return;
	}
    }
    else if(results["value"] == -1)
    {
	message = "Automatic Billing has been turned off for this product.";
	alert(message);
    }
    else if(results["value"] == 0)
    {
	message = "Automatic Billing has been unset for this product. The account level setting will now take precedence.";
	alert(message);
    }
}

function updateDomainProductRecurringBillingAll(value) {
    document.getElementById("LoadingDiv").style.display = 'block';
    getURL('/products-pricing/services/productCart.php?action=updatedomainproductrecurringbillingall&value='+value, updateDomainProductRecurringBillingAllHandler);
}

function updateDomainProductRecurringBillingAllHandler(status, content, contentType) {
    resetLoadingDiv();

    if(status != 200 && status != 0)
    {
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        return;
    }

    var message = "";
    if(results["value"] == 1)
    {
	message = "Automatic Billing has been turned on for all of your products.";
	if(!results["hasDefaultPaymentProfile"]) message += "\n\nAutomatic Billing will not function without a default billing profile. You will now be taken to a page that allows you to create one.";
	alert(message);
	if(!results["hasDefaultPaymentProfile"])
	{
	    window.location = "/management/payment-profiles.php#creditCardForm";
	    return;
	}
    }
    else if(results["value"] == -1)
    {
	message = "Automatic Billing has been turned off for all of your products.";
	alert(message);
    }
    else if(results["value"] == 0)
    {
	message = "Automatic Billing has been unset for all of your products. Your account default will now take precedence.";
	alert(message);
    }

    location.reload();
}

function updateDomainRecurringBillingAll(value) {
    document.getElementById("LoadingDiv").style.display = 'block';
    getURL('/products-pricing/services/productCart.php?action=updatedomainrecurringbillingall&value='+value, updateDomainRecurringBillingAllHandler);
}

function updateDomainRecurringBillingAllHandler(status, content, contentType) {
    resetLoadingDiv();

    if(status != 200 && status != 0)
    {
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        return;
    }

    var message = "";
    if(results["value"] == 1)
    {
	message = "Automatic Billing has been turned on for all of your domains.";
	if(!results["hasDefaultPaymentProfile"]) message += "\n\nAutomatic Billing will not function without a default billing profile. You will now be taken to a page that allows you to create one.";
	alert(message);
	if(!results["hasDefaultPaymentProfile"])
	{
	    window.location = "/management/payment-profiles.php#creditCardForm";
	    return;
	}
    }
    else if(results["value"] == -1)
    {
	message = "Automatic Billing has been turned off for all of your domains.";
	alert(message);
    }
    else if(results["value"] == 0)
    {
	message = "Automatic Billing has been unset for all of your domains. The account level setting will now take precedence.";
	alert(message);
    }

    location.reload();
}

function updateAccountRecurringBilling(value) {
    document.getElementById("LoadingDiv").style.display = 'block';
    getURL('/products-pricing/services/productCart.php?action=updateaccountrecurringbilling&value='+value, updateAccountRecurringBillingHandler);
}

function updateAccountRecurringBillingHandler(status, content, contentType) {
    resetLoadingDiv();

    if(status != 200 && status != 0)
    {
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        return;
    }

    var message = "";
    if(results["value"] == 1)
    {
	message = "Your account default for Automatic Billing has been set to enabled. Automatic Billing for Newly purchased products will be set to enabled as well. Products already in your account will keep their current settings.";
	if(!results["hasDefaultPaymentProfile"]) message += "\n\nAutomatic Billing will not function without a default billing profile. You will now be taken to a page that allows you to create one.";
	alert(message);
	if(!results["hasDefaultPaymentProfile"])
	{
	    window.location = "/management/payment-profiles.php#creditCardForm";
	    return;
	}
    }
    else if(results["value"] == 0)
    {
	message = "Your account default for Automatic Billing has been set to disabled. Automatic Billing for Newly purchased products will be set to disabled as well. Products already in your account will keep their current settings.";
	alert(message);
    }

    location.reload();
}

function updateDomainRecurringBilling(value, domainName) {
    document.getElementById("LoadingDiv").style.display = 'block';
    getURL('/products-pricing/services/productCart.php?action=updatedomainrecurringbilling&value='+value+'&name='+domainName, updateDomainRecurringBillingHandler);
}

function updateDomainRecurringBillingHandler(status, content, contentType) {
    resetLoadingDiv();

    if(status != 200 && status != 0)
    {
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        return;
    }

    var message = "";
    if(results["value"] == 1)
    {
	message = "Automatic Billing has been turned on for this domain.";
	if(!results["hasDefaultPaymentProfile"]) 
	{
	    message += "\n\nAutomatic Billing will not function without a default billing profile. You will now be taken to a page that allows you to create one.";
	    alert(message);
	    window.location = "/management/payment-profiles.php#creditCardForm";
	    return;
	}
//	alert(message);
    }
    else if(results["value"] == -1)
    {
	message = "Automatic Billing has been turned off for this domain.";
//	alert(message);
    }
    else if(results["value"] == 0)
    {
	message = "Automatic Billing has been unset for this domain. The account level setting will now take precedence.";
	alert(message);
    }
}

function swapRecurringBillingStats(elementId, domainName, type) {
    var status = document.getElementById(elementId).checked;
    getURL('/products-pricing/services/productCart.php?action=swaprecurringbillingstats&checked='+status+'&name='+domainName+'&type='+type, swapRecurringBillingStatsHandler);
}

function swapRecurringBillingStatsHandler(status, content, contentType) {
    if(status != 200 && status != 0)
    {
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        return;
    }
}

function processDotTelApplication(type, elementId) {
    var domainString = document.getElementById(elementId).value;

    domainString = domainString.split(".");
    domainString = domainString[0];
    domainString = domainString.replace(/[^a-zA-Z0-9\-]+/g,'');

    if(!domainString)
    {
        return;
    }

    if(type == "preregistration")
    {
        getURL('/products-pricing/services/productCart.php?action=checkpreorder&type='+type+"&name="+domainString+".tel", checkPreOrderHandler);
    }
    else
    {
        productCartSwap(true, domainString+".tel", 3, type, null, null, productCartSwapSimpleHandler, 1);
        window.location = "/checkout.php";
    }
}

function checkPreOrderHandler(status, content, contentType) {
    if(status != 200 && status != 0)
    {
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
        alert(results["message"]);
        return;
    }

    var name = results["name"];
    var type = results["type"];

    productCartSwap(true, name, 3, type, null, null, productCartSwapSimpleHandler, 1);
    window.location = "/checkout.php";
}

function isMouseLeaveOrEnter(e, handler) {
    if(e.type != 'mouseout' && e.type != 'mouseover')
        return false;

    var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;

    while (reltg && reltg != handler)
	reltg = reltg.parentNode;

    return (reltg != handler);
}

function createCustomPopupDiv(event, id, parentId, className, content) {
    var newDiv = document.createElement("div");
    var parent = document.getElementById(parentId);

    if(className)
        newDiv.setAttribute("class", className);

    newDiv.setAttribute("id", id);

    if(event)
    {
        var cursorPosition = getCursorPosition(event);

        newDiv.style.left = cursorPosition.x;
        newDiv.style.top = cursorPosition.y;
    }

    newDiv.innerHTML = unescape(content);
    parent.appendChild(newDiv);
    newDiv.style.display = "block";

}

function destroyCustomPopupDiv(id, parentId) {
    if(document.getElementById(id) && document.getElementById(parentId))
    {
        parentObj = document.getElementById(parentId);
        childObj = document.getElementById(id);
        parentObj.removeChild(childObj);
    }
}

function getCursorPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};

    if (e.pageX || e.pageY)
    {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    }
    else
    {
        var de = document.documentElement;
        var b = document.body;

        cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

    return cursor;
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

function processPromoCodeHandler(status, content, contentType) {
    if(status != 200 && status != 0)
    {
        alert("Something went wrong. Please refresh the page and try again. ("+status+")");
        document.getElementById("span_promo_code").style.display = "";
        document.getElementById("span_processing_promo").style.display = "none";
        return;
    }

    if(!content) return;

    var results = eval('('+content+')');
    var promoCodeApplicationArray = results["promoCodeApplicationArray"];
    var promoCodeApplicationArrayLength = promoCodeApplicationArray.length;

    for(var i = 0; i < promoCodeApplicationArrayLength; i++)
    {
	var spanName = "span_checkoutProductPrice_"+promoCodeApplicationArray[i]["type"]+"_"+promoCodeApplicationArray[i]["domain"];
	var spanNameHidden = "span_checkoutProductPriceHidden_"+promoCodeApplicationArray[i]["type"]+"_"+promoCodeApplicationArray[i]["domain"];

	if(document.getElementById(spanName))
	{
	    var spanElement = document.getElementById(spanName);
	    var spanElementHidden = document.getElementById(spanNameHidden);
	    spanElement.innerHTML = formatCurrency((spanElementHidden.innerHTML - promoCodeApplicationArray[i]["savings"]), true);
	    if(promoCodeApplicationArray[i]["savings"] > 0)
		spanElement.style.color = 'red';
	    else
		spanElement.style.color = '#000000';
	}

	if(document.getElementById("span_checkoutProductPriceHiddenAlternative_"+promoCodeApplicationArray[i]["domain"]))
	{
	    document.getElementById("span_checkoutProductPriceAlternative_"+promoCodeApplicationArray[i]["domain"]).innerHTML = formatCurrency((document.getElementById("span_checkoutProductPriceHiddenAlternative_"+promoCodeApplicationArray[i]["domain"]).innerHTML - promoCodeApplicationArray[i]["savings"]), true);
	    if(promoCodeApplicationArray[i]["savings"] > 0)
		document.getElementById("span_checkoutProductPriceAlternative_"+promoCodeApplicationArray[i]["domain"]).style.color = 'red';
	    else
		document.getElementById("span_checkoutProductPriceAlternative_"+promoCodeApplicationArray[i]["domain"]).style.color = '#000000';
	}
    }

    if(!results["productTotalPrice"]) results["productTotalPrice"] = 0;

    if(!results["status"])
     {
        if(document.getElementById("span_checkoutSavings")) document.getElementById("span_checkoutSavings").innerHTML = formatCurrency(0, true);
        if(document.getElementById("span_checkoutTotalCost")) document.getElementById("span_checkoutTotalCost").innerHTML = formatCurrency(results["productTotalPrice"], true);
        if(document.getElementById("span_namesafeShippingCost")) document.getElementById("span_namesafeShippingCost").innerHTML = formatCurrency(results["shippingCost"], true);
        if(results["message"]) alert(results["message"]);
        document.getElementById("span_promo_code").style.display = "";
        document.getElementById("span_processing_promo").style.display = "none";
        return;
    }

    var savings = results["savings"];

    if(document.getElementById("span_checkoutSavings"))
    {
        document.getElementById("span_checkoutSavings").innerHTML = formatCurrency(savings, true);

        if(savings)
	{
	    document.getElementById("span_checkoutSavings").style.color = "red";
	    document.getElementById("tr_checkoutSavings").style.display = "";
	}
    }

    if(document.getElementById("span_checkoutTotalCost")) document.getElementById("span_checkoutTotalCost").innerHTML = formatCurrency(results["productTotalPrice"], true);
    if(document.getElementById("span_namesafeShippingCost")) document.getElementById("span_namesafeShippingCost").innerHTML = formatCurrency(results["shippingCost"], true);

    currentPromoCode = results["promoCode"];

    document.getElementById("span_promo_code").style.display = "";
    document.getElementById("span_processing_promo").style.display = "none";

    var noPriceCheck = formatCurrency(results["productTotalPrice"], true);

    if(parseInt(noPriceCheck) == 0)
    {
	document.getElementById("payment_method_account_credit").checked = true;
	document.getElementById("zero_dollar_billing_message").style.display = "";
    }
    else
    {
	document.getElementById("zero_dollar_billing_message").style.display = "none";
    }
}

function adjustCartDuration(operator, cartId) {
    document.getElementById("span_durationControls_"+cartId).style.display = "none";
    document.getElementById("span_durationLoading_"+cartId).style.display = "";
    getURL('/products-pricing/services/productCart.php?action=adjustcartduration&operator='+operator+'&cartId='+cartId, adjustCartDurationHandler);
}

function adjustCartDurationHandler(status, content, contentType) 
{
    if(status != 200 && status != 0)
    {
        alert("Something went wrong. Please refresh the page and try again. ("+status+")");
        return;
    }

    var results = eval('('+content+')');
    var id = results["cartItemId"];

    if(!results["status"])
     {
        document.getElementById("span_durationControls_"+id).style.display = "";
        document.getElementById("span_durationLoading_"+id).style.display = "none";
        alert(results["message"]);
        return;
    }

    var name = results["name"];
    var type = results["type"];
    var price = results["newPrice"];
    var duration = results["newDuration"];

    var spanName = "span_checkoutProductPrice_"+type+"_"+name;
        
    if(document.getElementById(spanName))
    {
	var spanElement = document.getElementById(spanName);
        spanElement.innerHTML = formatCurrency(price, true);
	document.getElementById("span_checkoutProductPriceHidden_"+type+"_"+name).innerHTML = formatCurrency(price, true);
    }
    if(document.getElementById("span_checkoutProductPriceAlternative_"+name))
    {
        document.getElementById("span_checkoutProductPriceAlternative_"+name).innerHTML = formatCurrency(price, true);
        document.getElementById("span_checkoutProductPriceHiddenAlternative_"+name).innerHTML = formatCurrency(price, true);
    }

    setShoppingCartInfo(results["productTotalPrice"], results["productCount"]);

    if(document.getElementById("span_qty_"+name+id))
	document.getElementById("span_qty_"+name+id).innerHTML = duration;

    document.getElementById("span_durationControls_"+id).style.display = "";
    document.getElementById("span_durationLoading_"+id).style.display = "none";

    processPromoCode();
}

function processFastBuyAmazon(domain) {
    document.getElementById("LoadingDiv").style.display = 'block';
    getURL('/products-pricing/services/productCart.php?action=processfastbuyamazon&name='+domain, processFastBuyAmazonHandler);
}

function processFastBuyAmazonHandler(status, content, contentType) {
    if(status != 200 && status != 0)
    {
        alert("Something went wrong. Please refresh the page and try again. ("+status+")");
	resetLoadingDiv();
        return;
    }

    var results = eval('('+content+')');

    if(!results["status"])
    {
	if(results["redir"])
 	{
	    var confirmation = confirm(results["message"]);

	    if(!confirmation)
	    {
	 	resetLoadingDiv();
	        document.getElementById("check_"+results["name"]).checked = false;
	        return;
	    }

	    productCartSwap(0, results["name"], 1, "registration", "fast-buy", results["tld"], "", 1);
	    window.location = results["redir"];
	    return;
	}
	else
	{
            alert(results["message"]);
	}

	if(!results["accountId"])
	    location.reload();

        document.getElementById("check_"+results["name"]).checked = false;
        productCartSwap(0, results["name"], 1, "registration", "fast-buy", results["tld"], "", 1);
	resetLoadingDiv();
        return;
    }

    document.getElementById("check_"+results["name"]).checked = false;
    document.getElementById("check_"+results["name"]).disabled = true;
    document.getElementById("div_"+results["name"]).innerHTML = "Taken";
    document.getElementById("div_"+results["name"]).style.color = "red";
    resetLoadingDiv();
}

function productCartSwapAddOnDomain(add, name, duration, type, tag, tld, handler, notasync) {
    var action = "";
    if(!tag) tag = "";
    if(!tld) tld = "";
    if(!handler) handler = productCartSwapHandler;
    if(!notasync) notasync = 0;

    if(add)
	action = "add";
    else
	action = "remove";

    getURL('/products-pricing/services/productCart.php?action='+action+'&name='+name+'&duration='+duration+'&type='+type+'&tld='+tld+'&tag='+tag, handler, notasync);
}

function productCartSwapAddOnDomainHandler(status, content, contentType) {
    productCartSwapHandler(status, content, contentType, 1);
}

function productCartSwapAddOn(add, name, duration, type, tag, tld, handler, notasync) {
    var action = "";
    if(!tag) tag = "";
    if(!tld) tld = "";
    if(!handler) handler = productCartSwapHandler;
    if(!notasync) notasync = 0;

    if(add)
	action = "addaddon";
    else
	action = "removeaddon";

    getURL('/products-pricing/services/productCart.php?action='+action+'&name='+name+'&duration='+duration+'&type='+type+'&tld='+tld+'&tag='+tag, handler, notasync);
}

function productCartSwapAddOnHandler(status, content, contentType) {
    if(status != 200 && status != 0)
    {
        alert("Something went wrong. Please refresh the page and try again. ("+status+")");
	resetLoadingDiv();
        return;
    }

    if(!content)
	return;

    var results = eval('('+content+')');
    var action = results["action"];
    if(!results["status"])
    {
        alert(results["message"]);
        if(document.getElementById("check_addon_"+results["name"])) document.getElementById("check_addon_"+results["name"]).checked = false;
	resetLoadingDiv();
        return;
    }

    if(action == "remove")
        if(document.getElementById("check_addon_"+results["name"])) document.getElementById("check_addon_"+results["name"]).checked = false;
    else if(action == "add")
        if(document.getElementById("check_addon_"+results["name"])) document.getElementById("check_addon_"+results["name"]).checked = true;

    productCartSwapHandler(status, content, contentType);
}

function productCartSwapAddOnInlineHandler(status, content, contentType) {
    if(status != 200 && status != 0)
    {
        alert("Something went wrong. Please refresh the page and try again. ("+status+")");
	resetLoadingDiv();
        return;
    }

    if(!content)
	return;

    var results = eval('('+content+')');

    if(!results["status"])
    {
        alert(results["message"]);
        if(document.getElementById("check_"+results["name"])) document.getElementById("check_"+results["name"]).checked = false;
	resetLoadingDiv();
        return;
    }

    productCartSwapHandler(status, content, contentType, 0);
}
