// Functions for handling our fancy province/state/country boxes...
function currentSelection(selectBoxId) {
    // Retrieves the current selection of a select box...
    var selectBoxObj=document.getElementById(selectBoxId);
    return(selectBoxObj.options[selectBoxObj.selectedIndex].value);
}

function changeProv(newProv,provinceValueBoxId,countrySelectBoxId) {
    // Updates an edit box with the province when/if the country is Canada...
    if(currentSelection(countrySelectBoxId) != 'CA' && currentSelection(countrySelectBoxId) != 'IT') {
        // Country not CANADA...
        return(false);
    }
    // Update the box where our REAL province value lives (for submit)...
    document.getElementById(provinceValueBoxId).value=newProv;
    return(true);
}

function changeState(newState,stateValueBoxId,countrySelectBoxId) {
    // Updates an edit box with the state when/if the country is USA...
    if(currentSelection(countrySelectBoxId) != 'US') {
        // Country not USA...
        return(false);
    }
    // Update the box where our REAL state value lives (for submit)...
    document.getElementById(stateValueBoxId).value=newState;
    return(true);
}

function changeCountry(newCountry,baseProvinceBoxId) {
    // Shows/hides our province/state drop-downs depending on the country selected...
    /// ...and updates our actual edit/hidden box with the correct value for use on submit...
    if(baseProvinceBoxId != null) {
        if(newCountry == 'CA') {
            // Show province select box...
            $(baseProvinceBoxId).value = $('ca_'+baseProvinceBoxId).value;
            $(baseProvinceBoxId).hide();
            $('ca_'+baseProvinceBoxId).show();
            $('us_'+baseProvinceBoxId).hide();;
            $('it_'+baseProvinceBoxId).hide();
        } else if(newCountry == 'US') {
            // Show state select box...
            $(baseProvinceBoxId).value = $('us_'+baseProvinceBoxId).value;
            $(baseProvinceBoxId).hide();
            $('ca_'+baseProvinceBoxId).hide();
            $('us_'+baseProvinceBoxId).show();
            $('it_'+baseProvinceBoxId).hide();
        } else if(newCountry == 'IT') {
            // Show state select box...
            $(baseProvinceBoxId).value = $('it_'+baseProvinceBoxId).value;
            $(baseProvinceBoxId).hide();
            $('ca_'+baseProvinceBoxId).hide();
            $('us_'+baseProvinceBoxId).hide();
            $('it_'+baseProvinceBoxId).show();
        } else {
            // Show the plain ol' edit box...
            $(baseProvinceBoxId).show();
            $('ca_'+baseProvinceBoxId).hide();
            $('us_'+baseProvinceBoxId).hide();
            $('it_'+baseProvinceBoxId).hide();
        }
    }
    return(true);
}


/* sets Auto Renewal for cart
path: 		the ajax path to post to
enable: 	boolean
check:		the checkbox object
requires Prototype */
function cartAutoRenew(path, params, check) {
	params = $H(params);
	if (check.checked) 
		params.set("is_auto_renew_enabled", "1");
	else 
		params.set("is_auto_renew_enabled", "0");

	new Ajax.Request( path, {
		method: 'post', 
		parameters: params
	});
}

/* Sets or Unsets Auto Renwal for manage page 
path: 			the ajax path to post to
enable: 		boolean
requires Prototype */
function manageAutoRenew(path, enable) {
	new Ajax.Request( path, {
		method: 'post', 
		parameters: {'is_auto_renew_enabled': enable},
		evalJSON: true,
		onSuccess: function(transport) {
			var response = transport.responseJSON;
			if(response.success) {
				var id = response.id;
				var link = $("domainAutoRenew-"+id);
				var linkContent = link.down().down();
				if(response.is_auto_renew_enabled == 1 && !response.is_expired) {
					link.removeClassName("primary-small");
					link.addClassName("normal-small");
					linkContent.update("On");
					link.title = "Click to turn off auto renew"
					link.href = "javascript:manageAutoRenew('"+response.path+"',0);";
					$("domainStatus-"+id).update("Renews before " + response.date_expires);
				} else if (response.is_expired) {
					link.up().update("");
				} else {
					link.removeClassName("normal-small");
					link.addClassName("primary-small");
					linkContent.update("Off");
					link.title = "Click to turn on auto renew"
					link.href = "javascript:manageAutoRenew('"+response.path+"',1);";
					$("domainStatus-"+id).update("Domain Expires on " + response.date_expires);
				}
			} else {
				$('search_my_domains').insert('<p class="error_message">There was an error changing the auto renew state for '+response.domain_name+'.</p>', {position: 'before'});
			}
		}
	});
}

/* Fires the event for auto renewal set with the above function for all types specified on the manage page that match the state
requires Prototype */
function allAutoRenew(state, type) {
	var type = (type == null)?'domain': type; // in case old function call
	$$("a."+type+"AutoRenew").each(function(renew) {
		if ((renew.hasClassName('normal-small') > 0  && !state) || 
			(renew.hasClassName('primary-small') > 0 && state)) 
			eval(renew.href);
	});
}

/* check domain for trasnfering*/

function checkTransferabilitySingle(domain){
	new Ajax.Request( "/json/check_transferability", {
		method: 'post',
		parameters: { "domain_name": domain},
		evalJSON: true,
		onSuccess: function(transport) {
			var response = transport.responseJSON;
			$('exact_match-undetermined').hide();
			if (response.can_transfer == 1) {
				$("transfer-success").show();	
			} else {
				$("transfer-fail").show();	
			}
		}
	});
}


/* go through each domain in the domains hash and check to see if it's
 * transferable. requires domains hash to be present on page. 
 */ 
function checkTransferabilityBulk(){
	domains.each(function(domain) {
		new Ajax.Request( "/json/check_transferability", {
			method: 'post',
			parameters: {"domain_name": domain.key},
			evalJSON: true,
			onSuccess: function(transport) {
				var response = transport.responseJSON;
				if (response.can_transfer == 1) {
					$(response.domain_name + "-status").update(
						"Transferable for $" + domains.get(response.domain_name).get("price")
					);
					$(response.domain_name+"-checkbox").enable();
				} else if(response.is_success != 1) {
					$(response.domain_name+"-status").update("Error");
				} else {
					$(response.domain_name+"-status").update("Not Transferable");
				}
			},
			onFailure: function(transport) {
				var response = transport.responseJSON;
		
			}
		})
	});
}

function checkTransferabilityAlternate(domain) {
	new Ajax.Request( "/json/check_transferability", {
		method: 'post',
		parameters: { "domain_name": domain},
		evalJSON: true,
		onSuccess: function(transport) {
			var response = transport.responseJSON;
			if (response.can_transfer == 1) $("canTransfer").show();	
		}
	});
}


/* Function called from AJAX Return to update the search results list with the search result 
requires Prototype */
function updateDomain(transport) {
	checkDomainActive--;
	var myResponse = transport.responseJSON;
	var myDomain = domains.get(myResponse.domain_name);
	var myKey = myDomain.get("id");
	if (myKey == 'exact_match') {
		$('exact_match-undetermined').hide();
		if(myResponse.is_success) {
			if (myResponse.availability == 'available') {
				$('exact_match-success').show();
			} else {
				$('exact_match-sorry').show();
			}
		} else {
			$('exact_match-invalid').show();
		}
	} else {
		if(myResponse.is_success) {
			if (myResponse.availability == 'available') {
				$(myKey+'-checkbox').enable();
				$(myKey+'-status').update(myDomain.get("price"));
			} else {
				$(myKey+'-status').update("not available");
			}
		} else {
			$(myKey+'-status').update('<span class="status urgent">lookup failed</span>');
		}
	}
}

/* store the active AJAX domain checkx */
var checkDomainActive = 0;

function checkDomain(domain) {
	if (checkDomainActive < 2) {
		checkDomainActive++;
		new Ajax.Request("/json/check_availability", {
			method: 		'get',
			evalJSON: 		true,
			parameters:		{'domain_name':domain},
			onSuccess: 		updateDomain 
		});
	} else {
		setTimeout("checkDomain('"+domain+"')", 60);
	}
}

/* goes through all the domains in var domains on search results to actually lookup their availability 
requires Prototype */
function checkDomains() {
	domains.each(function(domain) {
		checkDomain(domain.key);
	});
}

function selectCartCard(select) {
	if ($F(select) > 0){
		$("payment_details").hide();
		for (var i = 1; i< select.options.length; i++) {
			var myOption = select.options[i];
			if(myOption.selected) {
				$("ccinfo-"+myOption.value).show();
			} else {
				$("ccinfo-"+myOption.value).hide();
			}
		}
	} else {
		for (var i = 1; i< select.options.length; i++) 
			$("ccinfo-"+select.options[i].value).hide();
		$("payment_details").show();
	}
}

/* shows the extra search results
requires Prototype */
function showHideResults(type) {
	var myEl = $('more_domains_'+type).toggle();
	if (myEl.visible()) 
		$('moreword_'+type).update('fewer');
	else
		$('moreword_'+type).update('more');
}

/* set all cheboxes with a speified class
on: boolean check or not
className: the class name given to all the checkboxes
requires Prototype */
function setChecks(state, className) {
	$$("input."+className).each(function(check) {
		if(!check.disabled) check.checked = state;	
	});
}

/* fire onclick event for checkboxes with a speified class
on: boolean check or not
className: the class name given to all the checkboxes
requires Prototype */
function fireChecks(state, className) {
	var checks = $$("input."+className);
	checks.each( function(check) {
		if(!check.disabled && check.checked != state) {
			check.checked = state;
			check.onclick();	
		}
	});
}

/* 
BULK MANAGEMENT TOOLS

the functions below rely on the following being set in the page:
domains: hash of domain:key
totalDomains: total of domains
domainCount: 1
updateType: what type of bulk action
continueBulk: switch for abort default: true
*/

/* launches modal dialog then updates domains with infor for 'type'
requires protopacked (Prototype & script.aculo.us) and Modalbox */
function bulkSubmit(type) {
	updateType = type;
	domainQueue = domains.keys();
	hasErrors = 0;
	continueBulk = true; // global
	domainCount = 1; // global
    formAddValues = new Hash(); // global

	if (totalDomains > 1)
		$('update-count').update("Setting first of "+totalDomains+" domains.");
	else if (totalDomains == 1)
		$('update-count').update("Setting one domain.");
	else {
		$('update-count').update("You didn't select any domains!");
		return;
	}


	Modalbox.show($('bulk-process'), {
		title: 'Setting your domains',
		width: 500,
		overlayClose: false,
		afterHide: bulkAbort,
		resizeDuration: 0,
		overlayDuration: 0,
		slideDownDuration: 0,
		slideUpDuration: 0,
		transitions: false
	});
	bulkAjax(domainQueue.pop());

}

/* launches modal dialog then adds each object of type secified that is chcked to cart
requires Prototype, script.aculo.us and Modalbox */
function bulkRenew(type) {
	var type = (type)?type:'domain'; // in case old function call
	domainQueue = new Array();
	eval(type+"s").each(function (domain) {
		var thisCheckState = $(domain.value.get("id")+'-check');
		if (thisCheckState.checked) 
			domainQueue.push(domain.key);
		});
	continueBulk = true;
	hasErrors = 0;

	totalDomains = domainQueue.length; // global
	domainCount = 1; // global
	updateType = 'renew'; // global

	if (totalDomains > 1)
		$('update-count').update("Setting first of "+totalDomains+" "+((type == "personal_name")?"personal names":"domains")+".");
	else if (totalDomains == 1)
		$('update-count').update("Setting one "+((type == "personal_name")?"personal name":"domain")+" for renewal.");
	else {
		$('update-count').update("You didn't select any "+((type == "personal_name")?"personal names":"domains")+"!");
		return;
	}

	Modalbox.show($('bulk-process'), {
        title: 'Setting your '+((type == "personal_name")?"personal names":"domains")+' for renewal',
		overlayClose: false,
		afterHide: bulkAbort,
		resizeDuration: 0,
		width: 500,
		overlayDuration: 0,
		slideDownDuration: 0,
		slideUpDuration: 0,
		transitions: false
	});

	$('view_cart_link').show(); // we're adding to cart, so show cart if it's not

	bulkAjax(domainQueue.pop(), type);
}

/* submits one bulk action at a time from hash of domains to submit 
requires prototype */
function bulkAjax(domain, type) {
	var type = (type)?type:'domain'; // in case old function call
	var ajaxPath; // where to post the ajax request
	var params;	// what params to send
	var collection = eval(type+"s"); // a Hash of domains is stored with name "types"

    if (domain) {
        if (updateType == 'renew') {
            ajaxPath =  "/shoppingcart/json/add_item";
            params = $H({
                'type'	: type,
                'name'	: domain,
                'action': collection.get(domain).get("action"),
                'period': collection.get(domain).get("minimum_renewal_period")
            });
			if (type == "personal_name") params.set("extra_params_email",  collection.get(domain).get("extra_params_email"));
        } else {
            ajaxPath =  "/manage/domain/" + domains.get(domain).get("id") + "/json/" + updateType;
            params = $('bulk-form').serialize(true);

            formAddValues.each( function (element) {
                params[ element.key ] = element.value;
            } );
        }

        $('update-count').update("Setting "+domainCount+" of "+totalDomains+" domains.");
        new Ajax.Request(ajaxPath, {
            method:     'post',
            evalJSON:   true,
            parameters:	params,
            onSuccess: bulkAjaxSuccess
        });
	} else { // we're done
		if (hasErrors == totalDomains && hasErrors > 1 && updateType != "renew") {
			$('update-count').update("All of your "+totalDomains+" domains had errors.");
			$("bulk-cancel-button").down().down().update("Return to page");
		}
		else {
			if (hasErrors) {
				if (totalDomains>1)
					$('update-count').update(hasErrors+" of "+totalDomains+" domains had errors. You can either stay on this page or continue");
				else
					$('update-count').update("Your one domain had an error. You can either stay on this page or continue");
				$("bulk-cancel-button").down().down().update("Return to page");
			} else { 
				$("bulk-cancel-button").hide();
				$('update-count').update("All Done");
			}
			$("bulk-continue-button").show();
		}
	}
	resizeCheck();
}

function bulkAjaxSuccess(response) {
    if (response.responseJSON.formAddValues) {
        formAddValues = $H( response.responseJSON.formAddValues );
    }

    if (response.responseJSON.error_is_fatal) {
        $('update-count').update("Bulk tool cannot continue.");
        continueBulk = false;
        if (response.responseJSON.redirect_url) {
            $('bulk-cancel-button').down().down().update('Continue');
            $('bulk-cancel-button').observe('click', function (event) {
                window.location.replace(response.responseJSON.redirect_url);
            });
        } else {
            $("bulk-cancel-button").down().down().update("Return to page");
        }
    }

	if(!response.responseJSON.success) { // error
		$('update-error').insert((response.responseJSON.domain_name?"While processing "+response.responseJSON.domain_name+", the following error was encountered: ":"")
			+response.responseJSON.message+"<br/>");	
		hasErrors++;
	}
	if (continueBulk) { 
		domainCount++; // increment domains
		bulkAjax(
			domainQueue.pop(), 
			(response.responseJSON.service_type)?response.responseJSON.service_type:'domain'
		);
	} else {
		continueBulk = true; // reset 
	}

	resizeCheck();
}

function resizeCheck() {
	Modalbox.resizeToContent();
	if ($('update-error').getHeight() > 300) 
		$('update-error').setStyle({
			height: '300px'
		});
		
}

// called as callback to modalbox hide
function bulkAbort() {
	continueBulk=false;
}


/* change Sort order/column for manage domain search results */
function sortBy(type) {
	var myForm = $("search_my_domains");
	var sortField = myForm.sort_by;
	sortField.value = type;
	myForm.submit();
}

/* store the active AJAX add to cart count */
var addToCartActive = 0;

/* add domain to cart from search page and transfers page
button-done and message-wait must be defined 
Prototype Required
*/
function addToCart(url, item_id_prefix) {

	$('button-done').hide(); // hide the add to cart button

	$('message-wait').show(); // show the 'please wait' message

	$(item_id_prefix + '-checkbox').disabled = true; // disable the checkbox we just checked

	if (addToCartActive < 1) {
		addToCartActive++;
		var item_cbox = $(item_id_prefix + '-checkbox');
		var remove_item = item_cbox.checked ? false : true;
		if (remove_item) url = url.replace(/add_item/, 'remove_item');
		var item_saved = $(item_id_prefix+'-saved');
		var item_error = $(item_id_prefix+'-error');
		new Ajax.Request(url, {
			method:     'get',
			evalJSON:   true,
			onSuccess : function (transport) {
				addToCartActive--;
				var response = transport.responseJSON;
				if (response.success != 0) {
					item_cbox.checked = remove_item ? false : true;
					item_saved.style.display = remove_item ? 'none' : 'inline';
					item_error.style.display = 'none';
				} else {
					item_cbox.checked = remove_item ? true : false;
					item_saved.style.display = remove_item ? 'inline' : 'none';
					item_error.style.display = 'inline';
					item_error.update(response.message);
				}
				item_cbox.disabled = false;
				$('button-done').show();
				$('message-wait').hide();
			}
		});
	} else { 
		setTimeout("addToCart('"+url+"','"+item_id_prefix+"')", 120);
	}
}

/* add service to cart from management page */
function addService(domain, type) {
	new Ajax.Request("/shoppingcart/json/add_item", {
		method:		'post',
		evalJSON:	true,
		parameters: {
			"name":		domain,
			"type":		"domain",
			"action":	"none"
			},
		onSuccess: function(transport) {
			// ignore errors as it's probably already added to cart
			window.location = "/shoppingcart/add_subitem/?name="+domain+"&type=domain&subitem_type="+type+"&action=none";
		}
	});
}


/* add or remove a DNS entry in DNS management style pages
NOTE: This aims to replace section_addline_javascript.tt2 zone methods
However, only advanced dns has been implemented so far
*/
function dnsAdd() {
	var type = arguments[0];
	var domain = false;
	if (arguments[1]) domain = arguments[1]; // see if domain was passed

	var tr = document.createElement('TR');
	Element.extend(tr); //prototype extend for IE
	$('zone_edit_cns_record_tbody').appendChild(tr);
	tr.update('\
		  <td><input type="text" name="'+type+'_subdomain" />'+(domain?'.'+domain:'')+'</td>\
		  <td><input type="text" name="'+type+'_ip_address" /></td>\
		  <td class="actions">\
			  <a href="#"\
			  onmousedown="dnsRemove(this,\'cns\')"\
			  class="remove">Remove</a>\
		  </td>\
		');
}
function dnsRemove(element, type) {
	Element.extend(element); // prototype extend for IE

	var tr = element.up().up(); // the row to remove
	var tbody = tr.up(); // the tbody that contains all the dns entries
	
	tr.remove();	// remove the dns entry from the table
}

/*
   Disables sections of a form based on which of two radio buttons is
   selected.
*/
function disable_form_sections( field_to_check, disable_fieldset, enable_fieldset ) {
    if ($(field_to_check).checked) {
        Form.enable(  $( enable_fieldset  ) );
        Form.disable( $( disable_fieldset ) );
    } else {
        Form.enable(  $( disable_fieldset ) );
        Form.disable( $( enable_fieldset  ) );
    }
}

/* toggle personal name results */
function togglePN() {
	$('show_personal_names').toggle();
	$('additional_personal_names').toggle();	
	$('hidePMlink').toggle();
}

