/* ------------------ PAYMENTS ------------------------ */

/* Global variable to hold the VAT multiplier rate passed in dynamically rather than a hard coded value */
var VAT_MULTI = 1;

function show_video(home_name) {
    document.getElementById('videoLightBox_Player').style.display = 'block';
    YAHOO.namespace('videoLightBox');
    YAHOO.videoLightBox.dialog = new YAHOO.widget.Dialog("videoLightBox", {
        width: "480px",
        fixedcenter: true,
        visible: false,
        draggable: true,
        modal: true,
        close: true,
        constraintoviewport: true
    });

    if (home_name == undefined || home_name == "") YAHOO.videoLightBox.dialog.setHeader("Advert Video");
    else YAHOO.videoLightBox.dialog.setHeader("Video for " + home_name);

    YAHOO.videoLightBox.dialog.render();
    YAHOO.videoLightBox.dialog.show();
}

function confirm_delete_video() {
    mySimpleDialog = new YAHOO.widget.Dialog("dlg", {
        width: "20em",
        fixedcenter: true,
        modal: true,
        visible: false,
        draggable: false
    });
    mySimpleDialog.setHeader("Warning!");

    mySimpleDialog.setBody("Are you sure you want to delete this video?<div style='text-align: right'>" +
	                       "<input type='button' id='confirm-button' value='Yes' onclick='handleYes();'>" +
	                       "<input type='button' id='cancel-button' value='Cancel' tabindex='1' onclick='handleNo();'>" +
	                       "</div>");
    handleYes = function() {
        return function() {
            mySimpleDialog.hide();
            document.getElementById("hdnDeleteVideo").value = "1";
            document.getElementById("manageForm").submit();
        };
    } ();

    handleNo = function() {
        return function() {
            mySimpleDialog.hide();
        };
    } ();

    mySimpleDialog.render(document.body);
    mySimpleDialog.show();
    document.getElementById("confirm-button").focus();
}

function toggleVideoUpload(isChecked) {
    document.getElementById('video').disabled = !isChecked;
    document.getElementById('imgUploadVideo').disabled = !isChecked;
    document.getElementById('txtVideoDescription').disabled = !isChecked;
    YAHOO.util.Dom.setStyle(['videoUploadTable'], 'opacity', isChecked ? 1 : 0.5);
}

function confirm_delete_wclink(linkId) {
    mySimpleDialog = new YAHOO.widget.Dialog("dlg", {
        width: "20em",
        fixedcenter: true,
        modal: true,
        visible: false,
        draggable: false
    });
    mySimpleDialog.setHeader("Warning!");

    mySimpleDialog.setBody("Are you sure you want to delete this link?<div style='text-align: right'>" +
	                       "<input type='button' id='confirm-button' value='Yes' onclick='handleYes();'>" +
	                       "<input type='button' id='cancel-button' value='Cancel' tabindex='1' onclick='handleNo();'>" +
	                       "</div>");
    handleYes = function() {
        return function() {
            mySimpleDialog.hide();
            document.getElementById("hdnDelete" + linkId).value = "1";
            document.getElementById("formList" + linkId).submit();
        };
    } ();

    handleNo = function() {
        return function() {
            mySimpleDialog.hide();
        };
    } ();

    mySimpleDialog.render(document.body);
    mySimpleDialog.show();
    document.getElementById("confirm-button").focus();
}

/* Move between paying quarterly and yearly */
function go_quarterly() {
	YAHOO.util.Dom.setStyle('quarterly', 'display', 'block');
	YAHOO.util.Dom.setStyle('yearly', 'display', 'none');
	document.getElementById('pay_freq').value = 'quarter';
	return false;
}

function go_yearly() {
	YAHOO.util.Dom.setStyle('quarterly', 'display', 'none');
	YAHOO.util.Dom.setStyle('yearly', 'display', 'block');
	document.getElementById('pay_freq').value = 'year';
	return false;
}

function toggleYearlyQuarterly() {
	var payFreq = $$("pay_freq");
	var autoRenew =$$("price_autornw");

	// Toggle the value of pay_freq.
	if (payFreq) {
		if (payFreq.value == "annual") {
			payFreq.value = "quarterly";
			// Auto renew is always off when in quarterly mode.
			if (autoRenew) {
				autoRenew.checked = false;
			}
		} else {
            payFreq.value = "annual";
		    // Do not reset AR, the user might have opted out.
		}
	}

	displayYearlyQuarterly();
}

function displayYearlyQuarterly() {
	var payFreq = $$("pay_freq");
	var annualPaymentTable = $$("annual_payment");
	var quarterlyPaymentTable = $$("quarterly_payment");

	// If there's a choice, display whichever payment table is indicated by the pay_freq value.
	if (annualPaymentTable && quarterlyPaymentTable) {
		if (payFreq && payFreq.value == "quarterly") {
			annualPaymentTable.style.display = "none";
			quarterlyPaymentTable.style.display = "block";
		} else {
			annualPaymentTable.style.display = "block";
			quarterlyPaymentTable.style.display = "none";
		}
	}

	// Need to recalculate list of selected options as the auto renew checkbox may have changed.
	fastTrackReCalculateSelectedOptions();
}

/* Submit the payment */
function submit_payment() {
	if (parseFloat(document.getElementById('tot').value) == 0) {
		alert('You must select at least one item to purchase');
		return false;
	} else {
		if (validateColocatedAdverts()) {
			return true;
		} else {
			alert("You must purchase a minimum of 2 Co-located Adverts for a set of co-located homes.");
			return false;
		}
	}
}

/* Make sure the human readable totals are correct, including VAT */
function update_total() {
	var vat = 1;
	if (document.getElementById('location').value == 'UK') {
		vat = VAT_MULTI;
	}
	var display = document.getElementById('total');
	var disVal = Math.round((parseFloat(document.getElementById('tot').value) * vat) * 100) / 100;
	display.innerHTML = disVal.toFixed(2);
	var display = document.getElementById('total_SB_now');
	var disSBNowVal = Math.round((parseFloat(document.getElementById('tot_SB_now').value) * vat) * 100) / 100;
	display.innerHTML = disSBNowVal.toFixed(2); 
	var display = document.getElementById('total_SB_next');
	var disSBNextVal = Math.round((parseFloat(document.getElementById('tot_SB_next').value) * vat) * 100) / 100;
	display.innerHTML = disSBNextVal.toFixed(2);
	checkSubOption();
}

function reset_totals() {
    document.getElementById('tot').value = "0";
    document.getElementById('tot_SB_now').value = "0";
    document.getElementById('tot_SB_next').value = "0";
}

/* Update a running total */
function change_total(id, value) {
	var el = document.getElementById(id);
	el.value = parseFloat(el.value) + value;
}

/* Check for only premium selected and show or hide subs accordingly */
function checkSubOption(){
	var bPremiumsChecked = $('input[id$=-pr]:checked').length>0;
	var bClassicsChecked = $("element[id$='-ad:selected']").length>0;
	var bPremplusChecked = $("element[id$='-pg:selected']").length>0;
	if(bPremiumsChecked && !bClassicsChecked && !bPremplusChecked){
		$("#subs_option").css("display", "block");
	} else {
		$("#subs_option").css("display", "none");
		$("#quarterly").css("display", "none");
		$("#yearly").css("display", "block");
	}
}

/* If we've disabled items to prevent them being selected without an advert, then activate them now. */
function allow_extras(home_id) {
	if (document.getElementById(home_id + '-link')) {
		document.getElementById(home_id + '-link').disabled = false;
		YAHOO.util.Dom.removeClass(home_id + '-linklabel', 'disabled');
	}
	if (document.getElementById(home_id + '-spot3')) {
		document.getElementById(home_id + '-spot3').disabled = false;
		YAHOO.util.Dom.removeClass(home_id + '-spot3label', 'disabled');
	}
	if (document.getElementById(home_id + '-spot6')) {
	    document.getElementById(home_id + '-spot6').disabled = false;
	    YAHOO.util.Dom.removeClass(home_id + '-spot6label', 'disabled');
	}
	if (document.getElementById(home_id + '-spot12')) {
	    document.getElementById(home_id + '-spot12').disabled = false;
	    YAHOO.util.Dom.removeClass(home_id + '-spot12label', 'disabled');
	}
	if (document.getElementById('-ofrcred1')) {
		document.getElementById('-ofrcred1').disabled = false;
		YAHOO.util.Dom.removeClass('-ofrcred1label', 'disabled');
	}
	if (document.getElementById('-ofrcred3')) {
		document.getElementById('-ofrcred3').disabled = false;
		YAHOO.util.Dom.removeClass('-ofrcred3label', 'disabled');
	}
	if (document.getElementById(home_id + '-webcreatornew')) {
		document.getElementById(home_id + '-webcreatornew').disabled = false;
		YAHOO.util.Dom.removeClass(home_id + '-webcreatornewlabel', 'disabled');
	}
	if (document.getElementById(home_id + '-webyear')) {
		document.getElementById(home_id + '-webyear').disabled = false;
		YAHOO.util.Dom.removeClass(home_id + '-webyearlabel', 'disabled');
	}
}

/* Disable extras if the home is unchecked */
function change_extras(home_id) {
	var classic  = document.getElementById(home_id + "-ad");
	var premium  = document.getElementById(home_id + "-pr");
	var premplus = document.getElementById(home_id + "-pg");  // Premium Advert Plus (was Premium Gold - hence "pg")
	
	var advertType;
	var basketContainsOneOrMorePremiumOrClassicAdverts = false;
	var basketContainsTwoOrMoreColoAdvertsFromTheSameSet = false;
	
	if (classic.checked || premium.checked || premplus.checked) {
		allow_extras(home_id);
	} else {
		disallow_extra(home_id + '-link');
		disallow_extra(home_id + '-spot3');
		disallow_extra(home_id + '-spot6');
		disallow_extra(home_id + '-spot12');
		
		// Iterate the items in the selected_items array ("basket"). If the item is a
		// Classic or Premium Advert or a Premium Advert Plus then set a flag. If it's
		// a Co-located Advert then determine whether there are any other Co-located
		// Adverts from the same set in the basket.
		for (var index in selected_items) {
			advertType = selected_items[index].split('-')[1];
			if (advertType == "ad" || advertType == "pr" || advertType == "pg") {
				basketContainsOneOrMorePremiumOrClassicAdverts = true;
				break;
			} else if (advertType == "coload") {
				// Count the number of checked Co-located Adverts in this set
				var parentId = selected_items[index].split('-')[3];
				if (countCheckedColoAdverts(parentId) >= 2) {
					basketContainsTwoOrMoreColoAdvertsFromTheSameSet = true;
					break;
				}
			}
		}
		
		// Determine whether there are any activate adverts on the Payments page. Do
		// this by finding out whether a Primary advert has been assigned.
		var pageContainsActiveAdverts = (primary_id > 0 ? true : false);
		
		// Enable or disable the Offer credits option
		if (basketContainsOneOrMorePremiumOrClassicAdverts == false && basketContainsTwoOrMoreColoAdvertsFromTheSameSet == false && pageContainsActiveAdverts == false) {
			disallow_extra('-ofrcred1');
			disallow_extra('-ofrcred3');
			disallow_extra(home_id + '-webcreatornew');
			disallow_extra(home_id + '-webyear');
		}
		checkSubOption();
	}
}

/* Helper function for above */
function disallow_extra(id) {
	var el = "";
	if (el = document.getElementById(id)) {
		if (el.checked == true) {
			el.checked = false;
			single_change(el);
		}
		el.disabled = true;
		YAHOO.util.Dom.addClass(id + 'label', 'disabled');
	}
}

/* If the link is paid for then they need to keep paying for it! */
function link_link(element) {
	var data = element.id.split("-");
	var home_id = data[0];
	var el = ""
	if (element.checked) {
		if (el = document.getElementById(home_id + '-link')) {
			if (el.checked == false) {
				el.checked = true;
				single_change(el);
			}
		}
	}
}

function recalculate_totals() {
	
	var element, price, priceSB, data, home_id, type, colo_parent_id, first_colo_in_set, add_colo_to_set
	var colo_parents = new Array();
	var assigned_primary = false;
	var colo_advert_counter = 0;
	
    reset_totals();
    selected_items.sort();
	
	// Find out whether the primary_id global variable has been set by payments.asp
    if (primary_id > 0) { assigned_primary = true; }
	
	// Loop through all the items (adverts, spotlights etc.) in the selected_items
	// array
    for (var index in selected_items) {
        element = document.getElementById(selected_items[index]);
        price = parseFloat(element.getAttribute('hl_price'));
        priceSB = parseFloat(element.getAttribute('hl_priceSB'));
		
        data = element.id.split("-");
        home_id = data[0];
        type = data[1];
		
		// For co-located adverts, find out whether this is the first selected
		// advert in the co-located set. If it is then set a flag so we know
		// whether or not to add in the cost of the parent.
		if (type == "coload") {
			colo_parent_id = data[3];
			add_colo_to_set = (add_colo_to_set||(element.getAttribute('add_colo')=="true"));
			first_colo_in_set = true;  // Assume true initially
			
			// Find out whether we've already hit the first co-located advert
			// in this set by looking in the array of stored parent ids.
			for (var i in colo_parents) {
				if (colo_parents[i] == colo_parent_id) {
					first_colo_in_set = false;
					break;
				}
			}
			
			// If this is the first co-located advert in the set then store the
			// parent id.
			if (first_colo_in_set) { colo_parents.push(colo_parent_id); }
		}
		
		// If this is a Single Home Premium or Classic Advert, or a Co-Located
		// Home Advert then we may need to adjust the pricing to account for
		// certain conditions: FIRST vs. EXTRA, PRICE vs. RENEW.
        if ((type == "ad") || (type == "pr") || (type == "pg") || (type == "coload")) {
			
			// Find out whether this is a renewal or an activation
			action = element.getAttribute('hl_action');
			
            if ((primary_id == home_id) || (primary_id == colo_parent_id) || !assigned_primary) {
				// This has been designated (or will henceforth be considered) the
				// FIRST (primary) Advert. For Classic/Premium adverts we can drop
				// out here because we can use the default prices from the
				// element's hl_price and hl_priceSB custom attributes.
                assigned_primary = true;
				
				// For Co-Located Home Adverts, however, we have the added
				// complication of determining whether to factor in the price of the
				// Parent Advert, which we do for the first advert and not adding additional
				if (type == "coload" && first_colo_in_set && !add_colo_to_set) {
					if (action == "activate") {
						price = pr_hcoload;
					} else {
						price = re_hcoload;
					}
				}
            } else {
				// This is an EXTRA (additional/secondary/not primary) advert. We
				// need to adjust the advert price to account for it's secondary
				// status (HL offer a discount for multiple adverts).
				if (type == "ad") {
					// Classic Advert - determine whether to use activation or
					// renewal price
                    if (action == "activate") {
                        price = pr_extraad;
                        priceSB = 0;
                    } else {
                        price = re_extraad;
                        priceSB = 0;
                    }
					
                } else if (type == "pr") {
					// Premium Advert - determine whether to use activation or
					// renewal price
                    if (action == "activate") {
                        price = pr_xpremad;
                        priceSB = pr_extraSB;
                    } else {
                        price = re_xpremad;
                        priceSB = re_extraSB;
                    }
				
				} else if (type == "pg") {
					// Premium Advert Plus.
					if (action == "renew_in_ren_win" || action == "activate") {
						price = pr_xprplus;
						priceSB = 0;
					}
				
                } else if (type == "coload" && first_colo_in_set && !add_colo_to_set) {
					// For Co-Located Home Adverts, factor in the price of the Parent
					// Advert for the first advert only if not adding as an additional
					if (action == "activate") {
						price = pr_xcoload;
					} else {
						price = re_xcoload;
					}
				}
            }
        }
        
		// Update the hidden form fields with the price(s) of this array item
        change_total('tot', price);
        change_total('tot_SB_next', priceSB);
		
        if (priceSB == 0) {
            change_total('tot_SB_now', price);
        } else {
            change_total('tot_SB_now', priceSB);
        }

    }

    update_total();
}

/* Add or remove an item from the basket. */
function single_change(element) {
    // Maintain a list of checked items for quick access
	if (element.checked) {
	    selected_items.push(element.id);
	} else {
	    for (var index in selected_items) {
	        if (selected_items[index] == element.id) {
	            selected_items.splice(index, 1);
	        }
	    }
	}

    // Go from this list and work everything out from scratch.
	recalculate_totals();
}

/* We want checkboxes that turn each off. This function also keeps a tally
   of the number of active adverts, which is used to determine when to
   enable/disable Other Product options */
function pretendRadio(element, home_id) {
	var classic  = home_id + "-ad";
	var premium  = home_id + "-pr";
	var premplus = home_id + "-pg";  // Premium Advert Plus (was Premium Gold - hence "pg")
	var otherElements = new Array();
	var activeAdverts = document.getElementById('hdn_active_adverts').value;
	
	if (element.id == classic) {
		otherElements[0] = document.getElementById(premplus);
		otherElements[1] = document.getElementById(premium);
	}
	
	if (element.id == premium) {
		otherElements[0] = document.getElementById(premplus);
		otherElements[1] = document.getElementById(classic);
	}
	
	if (element.id == premplus) {
		otherElements[0] = document.getElementById(premium);
		otherElements[1] = document.getElementById(classic);
	}		
	
	if (element.checked) {
	    for (var i = 0; i < otherElements.length; i++) {
            // Whoever wrote this code should have checked for existence before adding to the array
	        if (otherElements[i] == null)
	            continue;
			if (otherElements[i].checked == true) {
				otherElements[i].checked = false;
				single_change(otherElements[i]);
			} else {
				if (element.id == classic || element.id == premium || element.id == premplus) { activeAdverts++; }  // Add one to tally of active adverts
			}
		}
	} else {
		if (element.id == classic || element.id == premium || element.id == premplus) { activeAdverts--; }  // Subtract one from tally of active adverts
	}
	
	document.getElementById('hdn_active_adverts').value = activeAdverts;
}

//================================================================================

function validateColocatedAdverts() {
	
	//----------------------------------------------------------------------------
	// Checks to see that the minimum number of Co-located advert checkboxes have
	// been checked. Check takes place just prior to form submission. If the
	// advert is inactive then the Advertiser must choose a minimum of two adverts
	// to activate.
	//----------------------------------------------------------------------------
	
	if (document.getElementById("hdn_parent_adverts").value != "") {
		var arrParentAdverts = document.getElementById("hdn_parent_adverts").value.split(",");
		var colo_parent_id, set_is_partially_or_fully_active;
		
		for (var i = 0; i < arrParentAdverts.length; i++) {
			colo_parent_id = arrParentAdverts[i];
			set_is_partially_or_fully_active = document.getElementById("hdn_" + colo_parent_id + "_set_is_partially_or_fully_active").value;
			
			if (set_is_partially_or_fully_active == "false" && (countCheckedColoAdverts(colo_parent_id) == 1) ) {
				return false;
			}
		}
	}
	
	return true;
	
}

//================================================================================

function countCheckedColoAdverts(colo_parent_id) {
	
	//----------------------------------------------------------------------------
	// Loops through the Co-located advert checkboxes for the given Co-lo set
	// (parent) Id and counts how many are checked.
	//----------------------------------------------------------------------------
					
	var arrInputFields = document.getElementsByTagName("input");
	var count_checkboxes = 0;
	var number_colo_needed = 0;
	
	for (var i = 0; i < arrInputFields.length; i++) {
		//It is a checkbox
		if (arrInputFields[i].type == "checkbox") {
			//It is a colo check box
			if (arrInputFields[i].id.split("-")[1] == "coload") {
				//It is a colo checkbox belonging to our parent
				if(arrInputFields[i].id.split("-")[3] == colo_parent_id){	
					//It is ticked
					if (arrInputFields[i].checked) { count_checkboxes++; }
				}
			}
		}
	}
	
	return count_checkboxes;
}

//================================================================================

function enableDisableColoExtras(objChkBx) {

	//----------------------------------------------------------------------------
	// Determines whether a Co-lo set's Group Advert, Paid Link and Spotlight
	// options should be enabled or disabled based on whether the set is
	// active/inactive and a count of the set's checked Co-lo Advert checkboxes.
	//----------------------------------------------------------------------------

    var colo_parent_id = objChkBx.id.split("-")[3];
    var set_is_partially_or_fully_active = document.getElementById("hdn_" + colo_parent_id + "_set_is_partially_or_fully_active").value;
    var group_ad_is_active = document.getElementById(colo_parent_id + "-groupad-is-active").value;

	if (set_is_partially_or_fully_active == "true" || countCheckedColoAdverts(colo_parent_id) >= 2) {
		if (group_ad_is_active != "true") {
			enableOption(colo_parent_id, "groupad");
		}
		enableOption(colo_parent_id, "spot3");
		enableOption(colo_parent_id, "spot6");
		enableOption(colo_parent_id, "spot12");
		enableOption(colo_parent_id, "link");
    } else {
		disableOption(colo_parent_id, "groupad");
		disableOption(colo_parent_id, "spot3");
		disableOption(colo_parent_id, "spot6");
		disableOption(colo_parent_id, "spot12");
		disableOption(colo_parent_id, "link");
    }
}

//================================================================================

function enableDisableColoOtherProducts() {
	
	//----------------------------------------------------------------------------
	// Decides whether to enable or disable Other Products options by determining
	// whether either a) there are any Classic/Premium adverts in the "basket",
	// b) there are two or more Co-located Adverts from the dsame set in the
	// "basket" or c) there are any active Adverts on the Payments page; in any of
	// these cases the Other Products options should be available.
	//
	// Note that since this function is only used with Co-located Adverts, there's
	// no need to worry about handling the WebCreator options, only Offer Credits.
	//
	// Note also that Premium Advert Plus bundles are treated as Premium Adverts.
	//----------------------------------------------------------------------------
	
	var advertType;
	var basketContainsOneOrMorePremiumOrClassicAdverts = false;
	var basketContainsTwoOrMoreColoAdvertsFromTheSameSet = false;
	
	// Iterate the items in the selected_items array ("basket"). If the item is a
	// Classic or Premium Advert then set a flag. If it's a Co-located Advert then
	// determine whether there are any other Co-located Adverts from the same set
	// in the basket.
	for (var index in selected_items) {
		advertType = selected_items[index].split('-')[1];
		if (advertType == "ad" || advertType == "pr" || advertType == "pg") {
			basketContainsOneOrMorePremiumOrClassicAdverts = true;
			break;
		} else if (advertType == "coload") {
			// Count the number of checked Co-located Adverts in this set
			var parentId = selected_items[index].split('-')[3];
			if (countCheckedColoAdverts(parentId) >= 2) {
				basketContainsTwoOrMoreColoAdvertsFromTheSameSet = true;
				break;
			}
		}
	}
	
	// Determine whether there are any activate adverts on the Payments page. Do
	// this by finding out whether a Primary advert has been assigned.
	var pageContainsActiveAdverts = (primary_id > 0 ? true : false);
	
	// Enable or disable the Offer credits option
	if (basketContainsOneOrMorePremiumOrClassicAdverts || basketContainsTwoOrMoreColoAdvertsFromTheSameSet || pageContainsActiveAdverts) {
		// Enable
		if (document.getElementById('-ofrcred1')) {
			document.getElementById('-ofrcred1').disabled = false;
			YAHOO.util.Dom.removeClass('-ofrcred1label', 'disabled');
		}
		if (document.getElementById('-ofrcred3')) {
			document.getElementById('-ofrcred3').disabled = false;
			YAHOO.util.Dom.removeClass('-ofrcred3label', 'disabled');
		}
	} else {
		// Disable
		if (document.getElementById('-ofrcred1')) {
			document.getElementById('-ofrcred1').disabled = true;
			YAHOO.util.Dom.addClass('-ofrcred1label', 'disabled');
		}
		if (document.getElementById('-ofrcred3')) {
			document.getElementById('-ofrcred3').disabled = true;
			YAHOO.util.Dom.addClass('-ofrcred3label', 'disabled');
		}
	}
}

//================================================================================

function enableOption(id, type) {

	//----------------------------------------------------------------------------
	// Enables a payment option by enabling the option's checkbox and its
	// associated table cell.
	//----------------------------------------------------------------------------
	
	var objChkBx = document.getElementById(id + '-' + type);
	
	if (objChkBx) {
		objChkBx.disabled = false;
		YAHOO.util.Dom.removeClass(id + '-' + type + 'label', 'disabled');
	}
	
}

//================================================================================

function disableOption(id, type) {
	
	//----------------------------------------------------------------------------
	// Disables a payment option by disabling the option's checkbox and its
	// associated table cell. Also removes the item from the selected_items
	// array, forcing a recalculation of the Total value.
	//----------------------------------------------------------------------------
	
	var objChkBx = document.getElementById(id + '-' + type);
	
	if (objChkBx) {
		objChkBx.disabled = true;
		objChkBx.checked = false;
		YAHOO.util.Dom.addClass(id + '-' + type + 'label', 'disabled');
		single_change(objChkBx);
	}
	
}

//================================================================================

function handleColoRenewals(objChkBx, renewal_list, parent_id, group_advert_active_yn) {
	
	//----------------------------------------------------------------------------
	// Checks / unchecks all of the Co-located Adverts that are renewable within
	// a co-located set and recalculates the transaction total.
	//----------------------------------------------------------------------------
	
	var renewal_list_array = renewal_list.split(', ');
	var objRenewalChkBx, objRenewalHidden;
	
	// Loop through the IDs in the renewals list and create references to the
	// corresponding document elements: checkboxes *and* hidden form fields. Note
	// that hidden  fields are used to pass back form data since the renewal
	// checkboxes are disabled (to prevent advertisers from altering them), and
	// therefore can't post data back in the same way as activation checkboxes.
	for ( var i = 0; i < renewal_list_array.length; i++ ) {
		objRenewalChkBx = document.getElementById(renewal_list_array[i] + "-coload-" + (i + 1) + "-" + parent_id);
		objRenewalHidden = document.getElementById(renewal_list_array[i] + "-coload-" + (i + 1) + "-" + parent_id + "_hdn");
		
		// Check/uncheck the renewal checkbox and enable/disable the associated
		// hidden form field.
		if (objChkBx.checked) {
			objRenewalChkBx.checked = true;
			objRenewalHidden.disabled = false;
		} else {
			objRenewalChkBx.checked = false;
			objRenewalHidden.disabled = true;
		}
		
		// Update the transaction total
		single_change(objRenewalChkBx);
	}
	
	// Handle Group Advert renewal
	if (group_advert_active_yn == 1) {
		objRenewalChkBx = document.getElementById(parent_id + "-groupad");
		if (objChkBx.checked) {
			// Enable and pre-check the Group Advert checkbox and un-grey the
			// corresponding sales blurb
			objRenewalChkBx.checked = true;
			objRenewalChkBx.disabled = false;
			YAHOO.util.Dom.removeClass(parent_id + '-groupadlabel', 'disabled');
		} else {
			// Disable and uncheck the Group Advert checkbox and grey-out the
			// corresponding sales blurb
			objRenewalChkBx.checked = false;
			objRenewalChkBx.disabled = true;
			YAHOO.util.Dom.addClass(parent_id + '-groupadlabel', 'disabled');
		}
		
		// Update the transaction total
		single_change(objRenewalChkBx);
	}
}

//================================================================================

function preSelectProducts() {
	
	//----------------------------------------------------------------------------
	// Pre-selects products using a comma-delimited list passed in the querystring
	//----------------------------------------------------------------------------
	
	// Get list of products to pre-select from the querystring. This list should
	// be comma-delimited and contain products of the following format:
	// * <home_id>-<product_id> - home-specific product, e.g. Premium Advert
	// * <product_id>			- non-home-specific products, e.g. Deal Credit
	var preselectedProducts = window.location.search.substring(1).split("check=")[1].replace("%20", "");
	
	// Make sure the list of products isn't empty
	var arrPreselectedProducts;
	if (preselectedProducts.length == 0) {
		return false;
	} else {
		arrPreselectedProducts = preselectedProducts.split(",");
	}
	
	// Iterate the list of products to pre-select and prepend a "-" onto any
	// products which are non-home-specifc, i.e. they don't contain a "-"
	// seperator between home ID and product ID.
	for (var h = 0; h < arrPreselectedProducts.length; h++) {
		if (arrPreselectedProducts[h].indexOf("-") == -1) {
			arrPreselectedProducts[h] = "-" + arrPreselectedProducts[h];
		}
	}
	
	// Get all of the input elements on the page
	var arrInputFields = document.getElementsByTagName("input");
	
	// Iterate the input elements. Determine whether the input field is a checkbox
	// and, if so, whether the checkbox's ID contains the ID of any of the items
	// in our list of pre-selected products. Note that we use indexOf when
	// matching because COLOADs do not have the standard "<home_id>-<product_id>"
	// element IDs.	
	for (var i = 0; i < arrInputFields.length; i++) {
		var element = arrInputFields[i];
		if (element.type == "checkbox") {
			for (var j = 0; j < arrPreselectedProducts.length; j++) {
				if (element.id.indexOf(arrPreselectedProducts[j]) == 0) {
					
					// Get the home ID and product ID from the pre-selected product
					// name.
					var productParts = element.id.split("-");
					var homeId = productParts[0];
					var productId = productParts[1];
					var groupId;
					
					if (productId == "coload") {
						groupId = productParts[3];
					}
					
					if (productId != "" && productId != undefined) {
						
						// Pre-select the product by checking its checkbox
						element.checked = true;
						
						// Execute any onclick events associated with this
						// checkbox. Note that we can't use getAttribute to find
						// the onclick attribute as it's not cross-browser
						// compatible, so we iterate the element's attributes
						// instead.
						for (var k = 0; k < element.attributes.length; k++) {
							var attrib = element.attributes[k];
							if (attrib.name == "onclick") {
								eval(attrib.value.replace(/this/g, "element"));
							}
						}
						
						// Highlight the product's title
						if (document.getElementById("h3_" + arrPreselectedProducts[j])) {
							document.getElementById("h3_" + arrPreselectedProducts[j]).style.color = "red";
						}
						
						// Change the product line's background colour. Note that
						// this is handled slightly differently for co-lo
						// activations and renewals, as the co-lo children are
						// grouped within the same table row.
						if (productId == "coload") {
							if (document.getElementById("tr_" + groupId + "-set")) {
								document.getElementById("tr_" + groupId + "-set").style.backgroundColor = "#fffdef";
							}
						} else if (productId == "renewcolo") {
							if (document.getElementById("tr_" + homeId + "-set")) {
								document.getElementById("tr_" + homeId + "-set").style.backgroundColor = "#fffdef";
							}
						} else {
							if (document.getElementById("tr_" + arrPreselectedProducts[j])) {
								document.getElementById("tr_" + arrPreselectedProducts[j]).style.backgroundColor = "#fffdef";
							}
						}
					}
				}
			}
		}
	}
}

//================================================================================

function preSelectProductsDotNet() {

	//----------------------------------------------------------------------------
	// Similar to preSelectProducts(), but for the new-style .NET payments pages.
	//----------------------------------------------------------------------------
	
	// Get list of products to pre-select from the querystring - everything between "check=" and the next "&" (if any). 
	// This list should be comma-delimited and contain products of the following format:
	// * <home_id>-<product_id> - home-specific product, e.g. Premium Advert
	// * <product_id>			- non-home-specific products, e.g. Deal Credit
    var preselectedProducts = null;
    var queryCheck = window.location.search.substring(1).split("check=");
    if (queryCheck != null && queryCheck.length > 1) {
        preselectedProducts = queryCheck[1].split("&")[0];
    }

	// Make sure the list of products isn't empty
	var arrPreselectedProducts;
	if (!preselectedProducts ||preselectedProducts.length == 0) {
		return false;
	} else {
		preselectedProducts = preselectedProducts.replace("%20", "");
		arrPreselectedProducts = preselectedProducts.split(",");
	}

	// Convert the list of product IDs for the new .NET payments pages.
	var productId, newProductId, element;
	for (var h = 0; h < arrPreselectedProducts.length; h++) {
		if (arrPreselectedProducts[h].indexOf("-") == -1) {
			productId = arrPreselectedProducts[h];
		} else {
			productId = arrPreselectedProducts[h].split("-")[1];
		}

		switch (productId) {
		    case "premup"        : newProductId = "price_premup";   break;
		    case "pgup"          : newProductId = "price_pgup";     break;  
			case "pg"            : newProductId = "price_prplus";   break;
			case "pr"            : newProductId = "price_premad";   break;
			case "ad"            : newProductId = "price_firstad";  break;
			case "link"          : newProductId = "price_link_yes"; break;
			case "spot3"         : newProductId = "price_spot3";    break;
			case "spot6"         : newProductId = "price_spot6";    break;
			case "spot12"        : newProductId = "price_spot12";   break;
			case "ofrcred1"      : newProductId = "price_ofrcred1"; break;
			case "ofrcred3"      : newProductId = "price_ofrcred3"; break;
			case "webcreatornew" : newProductId = "price_webset";   break;
			case "webyear"       : newProductid = "price_webyear";  break;
			default: newProductId = productId;
		}
		
		element = document.getElementById(newProductId);
		
		if (element) {
			// Pre-select the product by checking its checkbox
			element.checked = true;
			
			// Execute any onclick events associated with this checkbox. Note that we
			// can't use getAttribute to find the onclick attribute as it's not
			// cross-browser compatible, so we iterate the element's attributes
			// instead.
			for (var k = 0; k < element.attributes.length; k++) {
				var attrib = element.attributes[k];
				if (attrib.name == "onclick") {
					eval(attrib.value.replace(/this/g, "element"));
					break;
				}
            }
            
            var container = getCollapsedContainerElement(element, 'div', 'collapsible2010col');
            if (container) {
                var head = container.previousSibling;
                if (head) {
                    var image = head.getElementsByTagName("img")[0];
                    container.className = 'collapsible2010exp';
                    image.src = '/images/dk2010/collapse.png'
                    image.alt = 'Collapse section'

                    if (head.lastChild) {
                        head.lastChild.innerHTML = head.lastChild.innerHTML.replace('Click here to upgrade', 'Upgrade');
                    }               
                }
            }
		}
	}
}

function getCollapsedContainerElement(node, tagName, className) {
    if (!node) return null;
    if (node.nodeType == 1 && (node.tagName.toLowerCase() == tagName.toLowerCase())) {
        if (className) {
            if (node.className.indexOf(className) != -1) {
                return node;
            }
        } else {
            return node;
        }
    }
    else {
        return getCollapsedContainerElement(node.parentNode, tagName, className);
    }
}



//================================================================================

function start_payments(vatRateMultiplier) {

    /*  Set the global variable so that any recalc/update methods can access it  */
    VAT_MULTI = vatRateMultiplier;
	
	var objPayFreq;
	
	if (objPayFreq = document.getElementById('pay_freq')) {  // Check for existence of pay_freq field
		if (objPayFreq.value == 'quarter') { go_quarterly(); }
		update_total();
	}
	
	// Check for the querystring parameter which indicates that we want to
	// pre-select one or more products.
	if (window.location.search.substring(1).indexOf("check=") != -1) {
		preSelectProducts();
	}
}

// **************************************************** pic uploading
function load_pic(my_id) {
//	var photo;
//	if (document.all) {
//		document.getElementById("upload" + my_id).style.visibility = "visible";
//		photo = document.getElementById("photo" + my_id)
//		photo.src = "file://" + document.getElementById("browse" + my_id).value;
//		photo.width = 140;
//		photo.height = 105;
//	}
	document.getElementById("warning" + my_id).style.visibility="visible";
}

var temp_cap = '';

//Make the temporary caption disappear and re-appear.
function cap_focus(element) {
	var cap_data = element.value.split(' ');
	if ((cap_data[0] == 'Enter') && (cap_data[1] == 'caption') && (cap_data[2] == 'here') && (cap_data[3] == 'for')) {
		temp_cap = element.value;
		element.value = '';
	} else {
		temp_cap = '';
	}
}

function cap_blur(element) {
	if ((element.value == '') && (temp_cap != '')) {
		element.value = temp_cap;
	}
}

// **************************************************** pic deleting
// Make an ajax call to delete a pic
function pic_delete_ajax(home_id, pic_id, session_id) {
    //if (confirm("Are you sure you wish to delete this photo? Press 'Cancel' if you do not wish to delete.")) {
    //Fire off delete command
    var surl = '/uh_ajax.asp?action=pic_delete&home_id=' + home_id + '&pic_id=' + pic_id + '&sid=' + session_id + '&t=' + getEpochTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', surl, { success: pic_delete_ajax_success, failure: pic_delete_ajax_error });

    // Wait screens
    YAHOO.util.Dom.setStyle('pic_wait', 'display', 'block');
    YAHOO.util.Dom.setStyle('pic_wait_p', 'display', 'block');

    // Clear errors
    YAHOO.util.Dom.setStyle('port_err', 'display', 'none');
    YAHOO.util.Dom.setStyle('empty_err', 'display', 'none');
    //}
}

// Handle when the ajax call to delete pic has been successful
function pic_delete_ajax_success(o) {
    var result = o.responseText;

    if (result != "") {
        document.getElementById('pic' + result).src = "/images/owners/no_photo.gif";
        YAHOO.util.Dom.setStyle('del' + result, 'display', 'none');
    } else {
        document.getElementById('port_err').innerHTML = "There was an unspecified problem - please go back to the Home Management page and try again.";
        YAHOO.util.Dom.setStyle('port_err', 'display', 'block');
    }

    // Remove wait screens
    YAHOO.util.Dom.setStyle('pic_wait', 'display', 'none');
    YAHOO.util.Dom.setStyle('pic_wait_p', 'display', 'none');
}

// Handle when the ajax call to delete pic has failed
function pic_delete_ajax_error() {
    document.getElementById('port_err').innerHTML = "There was an unspecified problem - please <a href='contactus.htm'>contact us</a> to let us know, quoting 'photo organiser delete error'.";
    YAHOO.util.Dom.setStyle('port_err', 'display', 'block');
}

// Ajax call to confirm deletion or display alert
function pic_delete(home_id, pic_id, session_id) {
    var surl = '/uh_ajax.asp?action=pic_delete_check&home_id=' + home_id + '&pic_id=' + pic_id + '&sid=' + session_id + '&t=' + getEpochTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', surl, { success: pic_delete_success, failure: pic_delete_error, argument: { prefix: home_id + "|" + pic_id + "|" + session_id} });

    // Wait screens
    YAHOO.util.Dom.setStyle('pic_wait', 'display', 'block');
    YAHOO.util.Dom.setStyle('pic_wait_p', 'display', 'block');

    // Clear errors
    YAHOO.util.Dom.setStyle('port_err', 'display', 'none');
    YAHOO.util.Dom.setStyle('empty_err', 'display', 'none');
}

// Handle when the ajax call to to confirm pic deletion has been successful
function pic_delete_success(o) {
    var result = o.responseText;
    var args = o.argument.prefix.split("|");

    if (result == "1") {
        pic_delete_confirm(args[0], args[1], args[2]);
    } else {
        pic_delete_disabled();
    }

    // Remove wait screens
    YAHOO.util.Dom.setStyle('pic_wait', 'display', 'none');
    YAHOO.util.Dom.setStyle('pic_wait_p', 'display', 'none');
}

// Handle when the ajax call to confirm pic deletion has failed
function pic_delete_error() {
    document.getElementById('port_err').innerHTML = "There was an unspecified problem - please <a href='contactus.htm'>contact us</a> to let us know, quoting 'photo organiser delete error'.";
    YAHOO.util.Dom.setStyle('port_err', 'display', 'block');
}


// Yui dialog to confirm deletion of pic
function pic_delete_confirm(home_id, pic_id, session_id) {
    mySimpleDialog = new YAHOO.widget.Dialog("dlg", {
        width: "21em",
        fixedcenter: true,
        modal: true,
        visible: false,
        draggable: false
    });
    mySimpleDialog.setHeader("Warning!");

    mySimpleDialog.setBody("Are you sure you wish to delete this photo?" +
							"<div style='text-align: right'>" +
							"<input type='button' id='confirm-button' value='Yes' onclick='handleYes();'>&nbsp;" +
							"<input type='button' id='cancel-button' value='Cancel' tabindex='1' onclick='handleNo();'>" +
							"</div>");

    handleYes = function() {
        return function() {
            mySimpleDialog.hide();
            pic_delete_ajax(home_id, pic_id, session_id);
        };
    } ();

    handleNo = function() {
        return function() {
            mySimpleDialog.hide();
        };
    } ();

    mySimpleDialog.render(document.body);
    mySimpleDialog.show();
    document.getElementById("cancel-button").focus();
}

// Yui dialog to alert pic cannot be deleted
function pic_delete_disabled() {
    mySimpleDialog = new YAHOO.widget.Dialog("dlg", {
        width: "35em",
        fixedcenter: true,
        modal: true,
        visible: false,
        draggable: false
    });
    mySimpleDialog.setHeader("Warning!");

    mySimpleDialog.setBody("Sorry, you cannot delete the first 8 photos and any photo used in a Spotlight." +
							"<div style='text-align: right'>" +
							"<input type='button' id='ok-button' value='Ok' tabindex='1' onclick='handleOk();'>" +
							"</div>");

    handleOk = function() {
        return function() {
            mySimpleDialog.hide();
        };
    } ();

    mySimpleDialog.render(document.body);
    mySimpleDialog.show();
    document.getElementById("ok-button").focus();
}

// **************************************************** pic swapping
function error_pic_swap() {
	document.getElementById('port_err').innerHTML = "There was an unspecified problem - please <a href='contactus.htm'>contact us</a> to let us know, quoting 'photo organiser error'.";
	YAHOO.util.Dom.setStyle('port_err', 'display', 'block');
}

function handle_pic_swap(o) {
    // Get the response. Its of the format pic_id1|pic_file1|del_yn1|pic_id2|pic_file2|del_yn2|allow_delete_pic_list|deny_delete_pic_list
    var result = o.responseText;
    var updates = result.split('|');
    if (updates.length == 8) {
        //Change photos
        document.getElementById('pic' + updates[0]).src = updates[1];
        document.getElementById('pic' + updates[3]).src = updates[4];

        //Alter orientations
        var pic1 = document.getElementById('box' + updates[0]);
        var pic2 = document.getElementById('box' + updates[3]);

        //Alter display of 'delete' link.
        if (YAHOO.util.Dom.get('del' + updates[0])) {
            if (updates[2] == "1") {                                                    // Pic deleted?
                YAHOO.util.Dom.setStyle('del' + updates[0], 'display', 'none');
            } else {
                YAHOO.util.Dom.setStyle('del' + updates[0], 'display', 'block');
            }
        }

        if (YAHOO.util.Dom.get('del' + updates[3])) {
            if (updates[5] == "1") {                                                    // Pic deleted?
                YAHOO.util.Dom.setStyle('del' + updates[3], 'display', 'none');
            } else {
                YAHOO.util.Dom.setStyle('del' + updates[3], 'display', 'block');
            }
        }

        //Make all delete links either active or inactive (if not in the first 8 and not used in spotlight).
        if (updates[6] != "") {
            var allowDeleteList = updates[6].split(',');
            for (i = 0; i < allowDeleteList.length; i++) {
                YAHOO.util.Dom.get('del' + allowDeleteList[i]).className = 'pic_delete_line';
            }
        }

        if (updates[7] != "") {
            var denyDeleteList = updates[7].split(',');
            for (i = 0; i < denyDeleteList.length; i++) {
                YAHOO.util.Dom.get('del' + denyDeleteList[i]).className = 'pic_delete_line_disabled';
            }
        }
        
        var temp = pic1.getAttribute('hl_orient');
        pic1.setAttribute('hl_orient', pic2.getAttribute('hl_orient'));
        pic2.setAttribute('hl_orient', temp);
    } else {
        document.getElementById('port_err').innerHTML = "There was an unspecified problem - please go back to the Home Management page and try again.";
        YAHOO.util.Dom.setStyle('port_err', 'display', 'block');
    }
    // Remove wait screens
    YAHOO.util.Dom.setStyle('pic_wait', 'display', 'none');
    YAHOO.util.Dom.setStyle('pic_wait_p', 'display', 'none');
}

function pic_swap(el1, pic2, home_id, sid) {
	var to_pic = document.getElementById(el1);
	var pic1 = to_pic.getAttribute('hl_pic');
	var from_pic = document.getElementById('box' + pic2);
	
	var bSwap = true;
	var orient = '';
	
	//If pic one is moving, look at incoming pic orientation
	if (parseInt(pic1) == 1) {
		orient = from_pic.getAttribute('hl_orient');
	} else if (parseInt(pic2) == 1) {
		orient = to_pic.getAttribute('hl_orient');
	}
	
	//Abort if we don't want them to do this. Technically this is bad, as our check should be server side but worst that can happen is messing up their ad.
	if (orient == "P") {
		YAHOO.util.Dom.setStyle('port_err', 'display', 'block');
		bSwap = false;
	} else if (orient == "?") {
		YAHOO.util.Dom.setStyle('empty_err', 'display', 'block');
		bSwap = false;			
	}
	
	if (bSwap) {
		//Fire off swap command and show saving thingy
	    var surl = '/uh_ajax.asp?action=pic_swap&home_id=' + home_id + '&pic1=' + pic1 + '&pic2=' + pic2 + '&sid=' + sid + '&t=' + getEpochTime();
		var request = YAHOO.util.Connect.asyncRequest('GET', surl, {success:handle_pic_swap,failure:error_pic_swap});
		
		// Wait screens
		YAHOO.util.Dom.setStyle('pic_wait', 'display', 'block');
		YAHOO.util.Dom.setStyle('pic_wait_p', 'display', 'block');
		
		// Clear errors
		YAHOO.util.Dom.setStyle('port_err', 'display', 'none');
		YAHOO.util.Dom.setStyle('empty_err', 'display', 'none');
	}

	//Move things back to where they should be
	from_pic.style.left = from_pic.getAttribute('hl_left');
	from_pic.style.top = from_pic.getAttribute('hl_top');
	from_pic.style.borderWidth = '';
	from_pic.style.padding = '';
	to_pic.style.borderWidth = '';
	to_pic.style.padding = '';
}

function init_pic_drags(home_id, sid) {
	var pic_i = 0; var pic_group = 'pics';
	for (var i=1; i<25; i++) {
		if (i < 21) {
			pic_i = i;
			pic_group = 'pics';
		} else {
			pic_i = 'p' + (i - 20);
			pic_group = 'pans';
		}
		pics[i] = new YAHOO.util.DD("box" + pic_i, pic_group);
		pics[i].onDragEnter = function(e, id) {
			document.getElementById(id).style.borderWidth = '5px;';
			document.getElementById(id).style.padding = '0px;';
		}
		pics[i].onDragOut = function(e, id) {
			document.getElementById(id).style.borderWidth = '';
			document.getElementById(id).style.padding = '';
		}
		pics[i].onInvalidDrop = function(e) {
			var el = this.getEl();
			el.style.top = el.getAttribute('hl_top');
			el.style.left = el.getAttribute('hl_left');
		}
		pics[i].startDrag = function(e) { var el = this.getEl(); el.style.zIndex = '9'; }
		pics[i].endDrag = function(e) { var el = this.getEl(); el.style.zIndex = ''; }
	}
	pics[1].onDragDrop = function (e, id) { pic_swap(id, 1, home_id, sid); }
	pics[2].onDragDrop = function (e, id) { pic_swap(id, 2, home_id, sid); }
	pics[3].onDragDrop = function (e, id) { pic_swap(id, 3, home_id, sid); }
	pics[4].onDragDrop = function (e, id) { pic_swap(id, 4, home_id, sid); }
	pics[5].onDragDrop = function (e, id) { pic_swap(id, 5, home_id, sid); }
	pics[6].onDragDrop = function (e, id) { pic_swap(id, 6, home_id, sid); }
	pics[7].onDragDrop = function (e, id) { pic_swap(id, 7, home_id, sid); }
	pics[8].onDragDrop = function (e, id) { pic_swap(id, 8, home_id, sid); }
	pics[9].onDragDrop = function (e, id) { pic_swap(id, 9, home_id, sid); }
	pics[10].onDragDrop = function (e, id) { pic_swap(id, 10, home_id, sid); }
	pics[11].onDragDrop = function (e, id) { pic_swap(id, 11, home_id, sid); }
	pics[12].onDragDrop = function (e, id) { pic_swap(id, 12, home_id, sid); }
	pics[13].onDragDrop = function (e, id) { pic_swap(id, 13, home_id, sid); }
	pics[14].onDragDrop = function (e, id) { pic_swap(id, 14, home_id, sid); }
	pics[15].onDragDrop = function (e, id) { pic_swap(id, 15, home_id, sid); }
	pics[16].onDragDrop = function (e, id) { pic_swap(id, 16, home_id, sid); }
	pics[17].onDragDrop = function (e, id) { pic_swap(id, 17, home_id, sid); }
	pics[18].onDragDrop = function (e, id) { pic_swap(id, 18, home_id, sid); }
	pics[19].onDragDrop = function (e, id) { pic_swap(id, 19, home_id, sid); }
	pics[20].onDragDrop = function (e, id) { pic_swap(id, 20, home_id, sid); }
	
	pics[21].onDragDrop = function (e, id) { pic_swap(id, 'p1', home_id, sid); }
	pics[22].onDragDrop = function (e, id) { pic_swap(id, 'p2', home_id, sid); }
	pics[23].onDragDrop = function (e, id) { pic_swap(id, 'p3', home_id, sid); }
	pics[24].onDragDrop = function (e, id) { pic_swap(id, 'p4', home_id, sid); }

}


// Uses an ajax call to refresh the resettable blocks within a single presenter
// path: The namespace of the presenter class being refreshed
// presenter: The name of the presenter class being refreshed
// formName: The html form containing the presenter
// waitImage: The image to show which the ajax call is in progress
function presenterBlocksAjax(path, presenter, formName, waitImage) {
	showWaitingImage(waitImage);

    // Post the presenter form to the ajax page, giving the type name of the presenter.
    YAHOO.util.Connect.setForm(formName);
    var url = "/ajax/Presenter_Ajax.aspx?p=" + path + "." + presenter + "&f=" + formName + "&ts=" + getEpochTime();
    YAHOO.util.Connect.asyncRequest("POST", url, {
        success: handlePresenterBlocksAjaxSuccess,
        failure: handlePresenterBlocksAjaxFailure, 
        argument: { presenter: presenter, waitImage: waitImage} });
}

function campaignPresenterBlocksAjax(path, presenter, formName, waitImage, args) {
	showWaitingImage(waitImage);
	YAHOO.util.Connect.setForm(formName);
	var url = "/ajax/Presenter_Ajax.aspx?p=" + path + "." + presenter + "&f=" + formName + "&ts=" + getEpochTime() + "&args=" + args;
	YAHOO.util.Connect.asyncRequest("POST", url, {
		success: handlePresenterBlocksAjaxSuccess,
		failure: handlePresenterBlocksAjaxFailure,
		argument: { presenter: presenter, waitImage: waitImage}
	});
}

function showWaitingImage(waitImage) {
	// Show any waiting image.
	var image = document.getElementById(waitImage);
	if (image != undefined) {
		image.style.display = "inline";
	}
}

function handlePresenterBlocksAjaxSuccess(response) {
    if (response.responseText != undefined) {
        var responseArray = response.responseText.split('|');
        if (responseArray[0] == 'Ok') {
            // Array elements with index 2,3,4,.. are expected to be html blocks to assign to blocks 0,1,2,.. etc.
            var i;
            for (i = 0; i + 2 < responseArray.length; i++) {
                var block = document.getElementById(response.argument.presenter + i);
				if(block){
					block.innerHTML = responseArray[i + 2]; 
				}
            }
        }

        // Hide any waiting image.
        var image = document.getElementById(response.argument.waitImage);
        if (image != undefined) {
            image.style.display = "none";
        }
    }
}

function handlePresenterBlocksAjaxFailure(response) {
    alert(response.responseText);
}

//TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT

//From uh_avail.aspx
function uh_avail_setup() {
	myindex = 0;
	warned = 0;


	//This number is the maximum number of selections - not likely to be greater than 500
	MAX_SELECTIONS=100;
	selarray = new Array(MAX_SELECTIONS);
	undo     = new Array(num_images-myoffset-1);

	i=0;
	sae = 1;

	AVAILABLE   = 0;
	UNAVAILABLE = 1;
	BOOKED      = 2;
	SELECTED    = 3;


	//Need to initialise to zero ...?
	for (i = 1; i < selarray.length ; i++)  {
		selarray[i] = 0;
	}

	for (i = myoffset+1; i < num_images ; i++)  {
		my_string = 'i' + i;
		undo[i-myoffset] = '' + document.getElementById(my_string).className;
	}

	classRSC = new Array(4);
		classRSC[UNAVAILABLE] = "u";
		classRSC[BOOKED] = "b";
		classRSC[AVAILABLE] = "a";
		classRSC[SELECTED] = "s";
}

function undome() {
	//alert('sae=' + sae);

	//Right, as our selections were added, we stored the previous value in the undo() array.
	//So replace the image with what was there before we overwrote it.

	var from_ptr;
	var to_ptr;
	var tmp_ptr;

	if (sae < 1) {
		sae = 1;
		alert("Nothing selected! UNDO YOUR LAST ACTION by selecting the group of dates and setting them to a booked or available.");
	}
	else {
		if (sae % 2 == 1) { 
			
			//It's even so take last two off
			//alert('sae odd=' + sae);
			sae--;
			to_ptr = selarray[sae];
			selarray[sae] = 0;
			
			sae--;
			from_ptr = selarray[sae];
			selarray[sae] = 0;

			if (to_ptr < from_ptr)  {
				//SWAP them
	
				tmp_ptr = from_ptr;
				from_ptr = to_ptr;
				to_ptr = tmp_ptr;
				//alert('swapped !!! from=' + from_ptr + ' to=' + to_ptr);
			}


//			alert ('from_ptr=' + from_ptr + ' to_ptr=' + to_ptr);
//			alert ('from_ptr plus myoffset=' + (from_ptr+myoffset) );
//			alert ('img' + (from_ptr + myoffset));

			for (i=from_ptr; i <= to_ptr; i++)  {
				document.getElementById('i' + (i + myoffset)).className = undo[i];
			}


		}
		else {
			//It's odd so just take one off
			
			//alert('sae even=' + sae);
			sae--;
			from_ptr = selarray[sae];
			document.getElementById('i' + (from_ptr + myoffset)).className = undo[from_ptr];
			//alert ('Setting image' + (from_ptr + myoffset) + '.src to undo[' + from_ptr + '] =' + undo[from_ptr]);
			selarray[sae] = 0;

		}
	}
	update_display();
}

function update_display() {
	//Update the display boxes and the images

	var tmp_string ='';
	var from_index=0;
	var to_index=0;
	var tmp_index=0;

	var j=0;

	//Display the array 
	document.myform3.myinput2.value = 'selarray: ' + tmp_string; 


	for (i = 1; i < selarray.length, selarray[i] != 0 ; i++)  {
		from_index=0;
		to_index=0;
		

		//Take the first pair
		from_index = selarray[i] + myoffset;
		//myform3.display1.value = 'disp1: img from_index=' + from_index + ' to_index=' + to_index + ' myoffset=' + myoffset + ' i=' + i + ' selarray=' + selarray[i]; 

		
		if ((i+1) < selarray.length && selarray[i+1] != 0)  {
			to_index = selarray[i+1] + myoffset;
		}
		else {
			to_index = 0;
		}

		//myform3.display2.value = 'disp2: img from_index=' + from_index + ' to_index=' + to_index + ' myoffset=' + myoffset + ' i=' + i + ' selarray=' + selarray[i]; 



		if ( to_index == 0 )  {
			// Just highlight the FROM index

//			myform3.display2.value = 'from1: img' + ' from_index=' + from_index + ' myoffset=' + myoffset + ' i=' + i + ' selarray=' + selarray[i]; 
			//Don't exceed No. of physical images
			if (from_index > num_images )  { from_index=num_images; alert('from index too big');}

//			myform3.display2.value = myform3.display2.value +  'from2: img' + ' from_index=' + from_index + ' myoffset=' + myoffset + ' i=' + i + ' selarray=' + selarray[i]; 


			if (from_index-myoffset > 0 )  {
				document.getElementById('i' + from_index).className = select_start_half(document.getElementById('i' + from_index).className);
				//Save the previous image value in our undo() array
				//undo[from_index] =  document.myform3['img' + from_index].src ;
				//alert('undo_index=' + from_index);
				
			}
		}
		else {
			//We're doing a pair so want to skip along a value
			i++;
		}

			
		if (to_index > num_images )  { to_index =num_images; }

		//alert ('from_index=' + from_index + ' to_index=' + to_index);

		// if to_index is a number ...

		if (to_index < from_index)  {
			//SWAP them

			tmp_index = from_index;
			from_index = to_index;
			to_index = tmp_index;
			//alert('swapped !!! from=' + from_index + ' to=' + to_index);
		}


		//alert('from=' + from_index + ' to=' + to_index);
		if (from_index-myoffset > 0)  {

			document.getElementById('i' + from_index).className = select_start_half(document.getElementById('i' + from_index).className);
			document.getElementById('i' + to_index).className = select_end_half(document.getElementById('i' + to_index).className);
			for (j=from_index+1; j < to_index; j++)  {
				//document.myform3['img' + j].src = imageAJF[SELECTED].src
				document.getElementById('i'+j).className = classRSC[SELECTED];
				//Save the previous image value in our undo() array
				//undo[ next index ] = j ;
			}
		}
	}

	//Do mydates which gets passed back to the ASP 
	tmp_string = '';
	for (i = 1; i < selarray.length, selarray[i] != 0 ; i++)  {
		tmp_string = tmp_string + (myoffset + selarray[i]) + ',';
	}
//	alert ('tmp_string=' + tmp_string);
 	document.getElementById('mydates').value = tmp_string;

}

function select_swap_half(class_in) {
	if (class_in=="us") { return "su"; }
	if (class_in=="bs") { return "sb"; }
	if (class_in=="as") { return "sa"; }
	return class_in;
	}
function select_start_half(class_in) {
	if ((class_in=="u") || (class_in=="ul")) { return "us"; }
	if ((class_in=="ub") || (class_in=="ubl")) { return "us"; }
	if ((class_in=="ua") || (class_in=="ual")) { return "us"; }
	if ((class_in=="b") || (class_in=="bl")) { return "bs"; }
	if ((class_in=="ba") || (class_in=="bal")) { return "bs"; }
	if ((class_in=="bu") || (class_in=="bul")) { return "bs"; }
	if ((class_in=="a") || (class_in=="al")) { return "as"; }
	if ((class_in=="ab") || (class_in=="abl")) { return "as"; }
	if ((class_in=="au") || (class_in=="aul")) { return "as"; }
	if (class_in=="su") { return "s"; }
	if (class_in=="sa") { return "s"; }
	if (class_in=="sb") { return "s"; }
	return class_in;
}
function select_end_half(class_in) {
	if ((class_in=="u") || (class_in=="ul")) { return "su"; }
	if ((class_in=="ub") || (class_in=="ubl")) { return "sb"; }
	if ((class_in=="ua") || (class_in=="ual")) { return "sa"; }
	if ((class_in=="b") || (class_in=="bl")) { return "sb"; }
	if ((class_in=="ba") || (class_in=="bal")) { return "sa"; }
	if ((class_in=="bu") || (class_in=="bul")) { return "su"; }
	if ((class_in=="a") || (class_in=="al")) { return "sa"; }
	if ((class_in=="ab") || (class_in=="abl")) { return "sb"; }
	if ((class_in=="au") || (class_in=="aul")) { return "su"; }
	class_in=select_swap_half(class_in);
	return class_in;
}

function go(img_src) {
	myindex = img_src - myoffset ;

	document.myform3.myinput1.value = myindex; 

	var tmp_string ='';

	if (sae < 1) {
		sae = 1;
	}

	//Add this index selection to our global array 

	//First make sure this isn't a mistaken double click
	if (selarray[sae-1]!=myindex) {
		selarray[sae] = myindex;
		sae++;
	
		//If latest addition makes it an even number i.e. it is the 2nd part of a pair AND 
		//it is less than the previous one then don't add this one and remove the 1st bit of the pair
		//and adjust the sae accordingly
	
		// (coz the array would usually start from 0
		if (sae % 2 == 1) { 
			//alert ('even');
			
			//If a user has clicked on one image 4 times then it won't undo with the first press.
			//So remove the latest pair if it's the same as the previous pair
			if ( sae >= 4 && sae > 1)  {
				if ( selarray[sae-1] == selarray[sae-3] && selarray[sae-2] == selarray[sae-4] )  {
					selarray[sae-1] = 0;
					selarray[sae-2] = 0;
					sae = sae - 2;
				}	
			}
		}
	} //if selarray[sae-1]!=myindex


	//alert ('calling update_display');
	update_display();

}

// HH stolen from http://www.somacon.com/p143.php
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
        return radioObj.value;
    else
        return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

// HH stolen from http://www.somacon.com/p143.php
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
    if (!radioObj)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}

function removeVideo() {
    var vid = document.getElementById('video_container');
    vid.removeChild(vid.childNodes[1]);
}

// From uh_identity.aspx
var emptyElement = document.createElement("input");
emptyElement.type = "hidden";

var $$ = function(id) {
    var el = YAHOO.util.Dom.get(id);
    return el ? el : emptyElement;
}

var elemExists = function(id) {
    var el = YAHOO.util.Dom.get(id);
    return el ? true : false;
}

function showOtherCardholder() {
    // Recalculate the current views and show/hide the appropriate sections of the page.
    updateViewState();
    reGenerateLookAfterPostback();
}

function identitySelected(user, identityId) {
    // Clear the new identity country selection dropdown.
    var dropDown = $$(user + "_country");
    dropDown.value = "Please Select";
    // Make an ajax call to populate the section's address lines with the data from the new identity.
    var session = getURLParam("mysess");
    var url = "/ajax/OwnerData_Ajax.aspx?&mysess=" + session + "&cmd=Identity&id=" + identityId;
    var request = YAHOO.util.Connect.asyncRequest('GET', url, { success: populateFormattedAddress, failure: showError, argument: { prefix: user} });
}

//Clears the corresponding identity selection (if any) and shows and collapses sections of the page.
function countryChanged(user) {
    // Get the new country selection dropdown changed.
    var dropDown = $$(user + "_country");
    // If an actual country has been selected then clear any selected identity.
    if (dropDown.value != "Please Select") {
        setCheckedValue(document.forms['identity_form'].elements['identity_' + user], '');
    }
    // Reset the section's address lines according to the selection.
    clearInputFields(user);
    // Recalculate the current views and show/hide the appropriate sections of the page.
    updateViewState();
    reGenerateLookAfterPostback();
}

//Function that reinvents viewstate, but not in the messy .NETty way. Used to redisplay the page in its previous state after postback.
//Sets postbackView, a hidden form field holding 2 comma separated values that holds state for owner and cardholder sections respectively.
//The views are:
//0 - Nothing is shown, i.e. the section is unnecessary (this view applies to the cardholder section only)
//1 - An identity has been selected by an established owner
//2 - An identity has been selected by an unestablished owner
//3 - No identity has been selected and no country has been selected (default when the owner has no identities)
//4 - No identity has been selected, the country selected is UK, QAS has returned 'normal' or 'no results', but no address has been selected
//5 - No identity has been selected, the country selected is UK, QAS has returned 'normal' or 'no results', and an actual address has been selected in the qas search results 
//6 - No identity has been selected, the country selected is UK, and *either* manual entry has been selected in the qas search results *or* QAS returned 'unavailable'
//7 - No identity has been selected and a country other than UK has been selected 
function updateViewState() {
    var ownerIdentity = getCheckedValue(document.forms['identity_form'].elements['identity_owner'])
    var ownerCountry = $$("owner_country").value;
    var ownerAddress = $$("select_owner").value;
    
    var oViewValue = calculateView(ownerIdentity, ownerCountry, ownerAddress);

    var otherCardholder = $$("use_other_cardholder").checked;
    var cardholderIdentity = getCheckedValue(document.forms['identity_form'].elements['identity_cardholder']);
    var cardholderCountry = $$("cardholder_country").value;
    var cardholderAddress = $$("select_cardholder").value;

    var cViewValue = 0;
    if (otherCardholder) {
        cViewValue = calculateView(cardholderIdentity, cardholderCountry, cardholderAddress);
    }
    
    // Set the postbackView field to hold the two views.
    $$("postback_view").value = oViewValue + "," + cViewValue;
    //alert($$("postback_view").value);
}

function calculateView(identity, country, address) {
    var isEstablished = $$("is_established").value;
    var qasUnavailable = $$("qas_error_unavailable").style.display;
    //alert(identity + "|" + country + "|" + address + "|" + isEstablished + "|" + qasUnavailable);
    // Work out the view for the owner section.
    if (identity != "") {
        if (isEstablished == "1") {
            view = 1;
        } else {
            view = 2;
        }
    } else { //No identity selected
        if (country != "Please Select") {
            if (textContains(country, "United Kingdom")) {
                if (qasUnavailable == "block" || address == "Enter address manually") {
                    view = 6; //Manual or error
                } else {
                    if (address != "") {
                        view = 5; //Address selected
                    } else {
                        view = 4;
                    }
                }
            } else { //Non UK address
                view = 7; 
            }
        } else { //No country selected
            view = 3;
        }
    }

    return view;
}

function clearInputFields(user) {
    // Clear all address lines.
    $$(user + "_title").selectedIndex = 0
    $$(user + "_forename").value = "";
    $$(user + "_surname").value = "";
    $$(user + "_telephone").value = "";
    $$(user + "_country_to_store").value = $$(user + "_country").value;
    $$(user + "_housename").value = "";
    $$(user + "_street").value = "";
    $$(user + "_housenumber").value = "";
    $$(user + "_county").value = "";
    $$(user + "_district").value = "";
    $$(user + "_flat").value = "";
    $$(user + "_postcode").value = "";
    $$(user + "_town").value = "";
    if (elemExists(user + "_dob_y")) {
        $$(user + "_dob_y").selectedIndex = 0;
        $$(user + "_dob_m").selectedIndex = 0;
        $$(user + "_dob_d").selectedIndex = 0;
    }
}

// Uses the postbackView hidden field to display blocks appropriately.
// Called at the end of page rendering to expand/collapse applicable fields based on the prepost state.
function reGenerateLookAfterPostback() {
    //alert ($$("postback_view").value);
    var postbackView = $$("postback_view").value.split(",");
    var oView = postbackView[0];
    var cView = postbackView[1];
    
    var ownerIdentity = getCheckedValue(document.forms['identity_form'].elements['identity_owner'])
    var cardholderIdentity = getCheckedValue(document.forms['identity_form'].elements['identity_cardholder'])
    var ownerCountry = $$("owner_country").value;
    var cardholderCountry = $$("cardholder_country").value;

    showAndHideSections("owner", oView);

    // Display the other cardholder checkbox if we have an owner address.
    if (oView == 1 || oView == 2 || oView == 5 || oView == 6 || oView == 7) {
        $$("use_other_cardholder_div").style.display = "block";
    } else {
        $$("use_other_cardholder_div").style.display = "none";
    }
    
    showAndHideSections("cardholder", cView);

    //Display the submit button if we have an owner address, and, if required, a cardholder address.
    if ((oView == 1 || oView == 2 || oView == 5 || oView == 6 || oView == 7) && (cView == 0 || cView == 1 || cView == 2 || cView == 5 || cView == 6 || cView == 7)) {
        $$("submit_button_div").style.display = "block"
    } else {
        $$("submit_button_div").style.display = "none"
    }
}

function showAndHideSections(user, view) {

    // Make sure the ajax controls are enabled.
    toggleAjaxEvents(user, true);
    
    // Make sure the ajax busy animation is hidden.
    $$("ajax_busy_" + user).style.display = "none";

    // Show and hide form sections based on the view.
    switch (view) {
        case "0":  //Show nothing
            $$(user + "_header").style.display = "none";
            $$("address_section_" + user).style.display = "none";
            break;
        case "1":  //Show just the header
            $$(user + "_header").style.display = "block";
            $$("address_section_" + user).style.display = "none";
            break;
        case "2":  //Show the header and address lines (collapsed where possible) so the unestablished owner can complete their identity
            $$(user + "_header").style.display = "block";
            $$("address_section_" + user).style.display = "block";
            $$("div_" + user + "_qas").style.display = "none";
            $$("div_" + user).style.display = "block";
            mandatoryLines(user); 
            collapsableShowAndHide(user, true);
            break;        
        case "3":  //Show just the header
            $$(user + "_header").style.display = "block";
            $$("address_section_" + user).style.display = "none";
            break;
        case "4":  //Show the header and the qas part of the address block
            $$(user + "_header").style.display = "block";
            $$("address_section_" + user).style.display = "block";
            $$("div_" + user + "_qas").style.display = "block";
            $$("div_" + user).style.display = "none";
            break;
        case "5":  //Show the header, the qas part, and the address lines, collapsed where possible
            $$(user + "_header").style.display = "block";
            $$("address_section_" + user).style.display = "block";
            $$("div_" + user + "_qas").style.display = "block";
            $$("div_" + user).style.display = "block";
            mandatoryLines(user);
            collapsableShowAndHide(user, true); 
            break;
        case "6":  //Show the header, the qas part, and the uncollapsed address lines
            $$(user + "_header").style.display = "block";
            $$("address_section_" + user).style.display = "block";
            $$("div_" + user + "_qas").style.display = "block";
            $$("div_" + user).style.display = "block";
            mandatoryLines(user);
            collapsableShowAndHide(user, false);
            break;
        case "7":  //Show the header and the uncollapsed address lines part of the address block for non-UK customers
            $$(user + "_header").style.display = "block";
            $$("address_section_" + user).style.display = "block";
            $$("div_" + user + "_qas").style.display = "none";
            $$("div_" + user).style.display = "block";
            mandatoryLines(user);
            collapsableShowAndHide(user, false);
            break;
        default:
            break;
    }
}

function mandatoryLines(user) {
    // Display variable address line mandatory flags depending on address country (only relevent for views 2, 5, 6, & 7).
    if (textContains($$(user + "_country_to_store").value, "United Kingdom")) {
        // For a UK address just the postcode is required.
        $$(user + "_house_mand").style.display = "none";
        $$(user + "_street_mand").style.display = "none";
        $$(user + "_town_mand").style.display = "none";
        $$(user + "_postcode_mand").style.display = "inline";
    } else {
        // For a non-UK address, we don't need post code but we must have street, town, and one of flat/house number/house name.
        $$(user + "_house_mand").style.display = "inline";
        $$(user + "_street_mand").style.display = "inline";
        $$(user + "_town_mand").style.display = "inline";
        $$(user + "_postcode_mand").style.display = "none";
    }
}

// Enables us to hit the enter key at QAS search without submitting the page form
function checkQASReturn(e, id) {
    var characterCode
    if (e && e.which) { //if which property of event object is supported (NN4)
        e = e
        characterCode = e.which //character code is contained in NN4's which property
    } else {
        e = event
        characterCode = e.keyCode //character code is contained in IE's keyCode property
    }

    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        qasAddressSearch(id);
        return false;
    }    
    return true;
}

//Neat way of getting the URL parameter in javascript
function getURLParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

// Enable/disable QAS search elements as appropriate. 
// Used to show the 'waiting' animation and disable the other controls while waiting for an ajax response (i.e. when qasAddressSearch or qasGetAddress are called).
function toggleAjaxEvents(user, enabled) {
    $$("select_" + user).disabled = !enabled;
    $$("lookup_" + user).src = enabled ? 'images/buttons10/g-find-address-white.png' : 'images/buttons10/dis-find-address-white.png';
    $$("lookup_" + user).onclick = enabled ? function() { qasAddressSearch(user) } : null;
}

// Does the ajax call to fill the select list with partial addresses.
function qasAddressSearch(user) {
    // Replace the select list with the ajax busy animation and disable the qas controls.
    $$("select_" + user).style.display = "none";
    $$("ajax_busy_" + user).style.display = "block";
    toggleAjaxEvents(user, false);

    // Make the ajax call.
    var session = getURLParam("mysess");
    var postcode = $$("postcode_" + user + "_qas").value;
    var url = "/ajax/AddressSearch_Ajax.aspx?mysess=" + session + "&p=" + postcode;
    var request = YAHOO.util.Connect.asyncRequest('GET', url, { success: populateDropdownList, failure: showError, argument: { prefix: user} });
}

// Does the ajax call to get a full 8 line address from a selected partial address.
function qasGetAddress(select, user) {
    if (select.value != "Enter address manually") {
        // Disable the qas controls.
        toggleAjaxEvents(user, false);

        // Make the ajax call.
        var moniker = select.value;
        var session = getURLParam("mysess");
        var url = "/ajax/AddressSearch_Ajax.aspx?mysess=" + session + "&m=" + moniker;
        var request = YAHOO.util.Connect.asyncRequest('GET', url, { success: populateFormattedAddress, failure: showError, argument: { prefix: user} });
    } else {
        // Recalculate the current views and show/hide the appropriate sections of the page.
        clearInputFields(user);
        updateViewState();
        reGenerateLookAfterPostback();
    }
}

// Fills the select list with partial addresses.
function populateDropdownList(response) {
    //alert(response.argument.prefix + response.responseText);
    var user = response.argument.prefix; //either "owner" or "cardholder"
    var responseArray = response.responseText.split("|", 3);

    if (responseArray[0] == "Normal") {
        $$("qas_error_unavailable").style.display = "none";
        $$("qas_error_noresults").style.display = "none";
        // Show the addresses in the list. Wrap in a try-catch to make sure we refresh the page properly whatever happens.
        try {
            var selectElement = $$("select_" + user);
            selectElement.style.display = "block";
            json = YAHOO.lang.JSON.parse(responseArray[2]);
            // Wipe the existing select list clean or we will just append to it.
            $$("select_" + user).innerHTML = "";

            // Iterate through the json response adding an option for each partial address.
            for (var i = 0, len = json.length; i < len; i++) {
                var address = json[i];
                var moniker = address.Moniker;
                var address = address.PartialAddress;
                var ruler = $$("ruler");
                // Tape measure the string length.
                ruler.innerHTML = address;
                if (ruler.offsetWidth > 400) {
                    //The return string was too wide, so chop it off just under 500px and append "..."
                    address = truncateString(address, 1, 2, 400) + "...";
                }
                ruler.innerHTML = "";
                // Create an option element and append it to the select element.
                var option = document.createElement("option");
                option.text = decodeURI(address);
                option.value = moniker;
                selectElement.options.add(option);
            }

            // Add a final option for manual address entry.
            var option = document.createElement("option");
            option.text = "Enter address manually";
            option.value = "Enter address manually";
            selectElement.options.add(option);
        } catch (ex) {
            showError();
            return;
        }
    } else {
        if (responseArray[0] == "NoResult") {
            showNoResults(responseArray[1]);
            return;
        } else {
            showUnavailable(responseArray[1]);
            return;
        }
    }
    
    // Recalculate the current views and show/hide the appropriate sections of the page.
    updateViewState();
    reGenerateLookAfterPostback();
}

//Truncates a string at the closest length in pixel less than cuttOffLength
//original - the string to truncate
//fraction - The fraction of the string length 0 being nothing and 1 being the full string
//factor - A 2^n incrementing value used to narrow down the fraction to the half 
//of the remaining part. 1 - (1/2^1) + (1/2^2) + (1/2^3) + ... + (1/2^n) < 1
function truncateString(original, fraction, factor, cutOffLength) {
    //Get the ruler span which is a hidden html element in the page
    var ruler = $$("ruler");
    //Get the test value. On first iteration 50% on second +/- 25% on third +/- 12.5% etc
    var truncatedText = original.substring(0, Math.floor(original.length * fraction));
    ruler.innerHTML = truncatedText
    //If it's a close hit or if the recursion has gone too deep, return value
    if (Math.abs(cutOffLength - ruler.offsetWidth - 3) <= 3 || (factor > 2048 && ruler.offsetWidth < cutOffLength)) {
        return truncatedText;
    }
    
    //Increment or decrement fraction with regards to its length
    if (ruler.offsetWidth > cutOffLength) {
        fraction -= (1 / factor);
    } else {
        fraction += (1 / factor);
    }
    //And off we go for another try
    return truncateString(original, fraction, factor * 2, cutOffLength);
}

//Populates the address form inpput fields
function populateFormattedAddress(response) {
    var user = response.argument.prefix; //either "owner" or "cardholder"
    var responseArray = response.responseText.split("|", 3);
    
    if (responseArray[0] == "Normal" || responseArray[0] == "Ok") {
        // Populate the addresses fields. Wrap in a try-catch to make sure we refresh the page properly whatever happens.
        if (responseArray[0] == "Normal") {
            $$("qas_error_unavailable").style.display = "none";
            $$("qas_error_noresults").style.display = "none";
        }
        try {
            // Populate the address lines with values from the expected JSON response.
            var json = YAHOO.lang.JSON.parse(responseArray[2]);
            if (json.FirstName || json.Surname) {
                $$(user + "_title").value = json.Title;
                $$(user + "_forename").value = json.FirstName;
                $$(user + "_surname").value = json.Surname;
                $$(user + "_telephone").value = json.Landline;
                $$(user + "_country_to_store").value = json.Country;
                if (json.DateOfBirth_Y) {
                    $$(user + "_dob_y").value = json.DateOfBirth_Y;
                    $$(user + "_dob_m").value = json.DateOfBirth_M;
                    $$(user + "_dob_d").value = json.DateOfBirth_D;
                }
            } else {
                $$(user + "_country_to_store").value = $$(user + "_country_to_store").value;
            }
            $$(user + "_housename").value = json.BuildingName;
            $$(user + "_street").value = json.Street;
            $$(user + "_housenumber").value = json.BuildingNumber;
            $$(user + "_county").value = json.County;
            $$(user + "_district").value = json.District;
            $$(user + "_flat").value = json.Flat;
            $$(user + "_postcode").value = json.PostCode;
            $$(user + "_town").value = json.TownOrCity;
        } catch (ex) {
            showError();
            return;
        }
    } else {
        if (responseArray[0] == "NoResult") {
            showNoResults(responseArray[1]);
            return;
        } else {
            showUnavailable(responseArray[1]);
            return;
        }    
    }

    // Recalculate the current views and show/hide the appropriate sections of the page.
    updateViewState();
    reGenerateLookAfterPostback();
}

// Hide/unhide empty collapsable address lines.
function collapsableShowAndHide(user, hide) {
    //Don't hide for non-uk identities
    hide = hide && ($$(user + "_country_to_store").value == "United Kingdom");
    //Thanks IE! Have to do this the awkward way rather than using getElementByClassName
    var tableRows = document.getElementsByTagName("tr");
    for (var i in tableRows) {
        if (tableRows[i].className != null && textContains(tableRows[i].className, user + "_collapsable")) {
            if (tableRows[i].id != null) {
                var inputElem = $$(tableRows[i].id.replace("_tr", ""));
                tableRows[i].style.display = (inputElem.value != "" || !hide ? "" : "none");
            }
        }
    }
}

//Something ajaxy or form detaily has gone wrong on the client side, so show error
function showUnavailable(msg) {
    // Show the error.
    $$("qas_error_unavailable").innerHTML = msg;
    $$("qas_error_unavailable").style.display = "block";
    $$("qas_error_noresults").style.display = "none";

    // Recalculate the current views and show/hide the appropriate sections of the page.
    updateViewState();
    reGenerateLookAfterPostback();
}

function showNoResults(msg) {
    // Show the error.
    $$("qas_error_noresults").innerHTML = msg;
    $$("qas_error_noresults").style.display = "block";
    $$("qas_error_unavailable").style.display = "none";

    // Recalculate the current views and show/hide the appropriate sections of the page.
    updateViewState();
    reGenerateLookAfterPostback();
}

function showError() {
    showUnavailable("Something went wrong when retrieving your address. Please try again or enter it manually.");
}

//returns true if searchString is a substring of text parameter
function textContains(text, searchString) {
    return (text.indexOf(searchString) != -1);
}

function setOpacity(element, opacity) {
	YAHOO.util.Dom.setStyle(element.id, 'opacity', opacity / 100); 
}

// Expand/collapsible accordion page functions. 
// These are not as generic as they might be. Really, this is all specific to the account details page, but there's definitely room for improvement.

// The name of the accordion page we're on, used to build control ids etc.
var accordionPage;
// An array of YAHOO.widget.Module objects comprising the accordion page.
var accordionModules;

//
// expand the content within the accordion module given by its positional index.
function accordionExpand(index) {
    // expand the accordion module.
    accordionModules[index].className = 'collapsible2010exp';
    var previousSibling = accordionModules[index].previousSibling;
    if (previousSibling) {
        var childNodes = previousSibling.childNodes;
        if (childNodes) {
            var image = childNodes[0];
            if (image) {
                image.src = '/images/dk2010/collapse.png'
                image.alt = 'Collapse section'
            }
        }
    }
}

//
// collapse the content within the accordion module given by its positional index.
function accordionCollapse(index) {
    // Collapse the accordion module.
    accordionModules[index].className = 'collapsible2010col';
    var previousSibling = accordionModules[index].previousSibling;
    if (previousSibling) {
        var childNodes = previousSibling.childNodes;
        if (childNodes) {
            var image = childNodes[0];
            if (image) {
                image.src = '/images/dk2010/expand.png'
                image.alt = 'Expand section'
            }
        }
    }
}

// The onclick function for all accordion page modules' Save buttons, regardless of their display image.
function accordionSave(formName, index) {
    // Get the post parameter from the page.
    var postParameter = document.getElementById("postParameter_" + index).value;
    // Post the presenter's values via an ajax call.
    accordionModulePost(formName, index, postParameter);
}

// The onclick function for all accordion page modules' Cancel buttons.
function accordionCancel(index) {
    // Reset the presenter's default values via an ajax call.
    accordionModulePost("default_form_" + index, index, "");
    // Collapse the accordion module.
    accordionCollapse(index);
    // Hide any previously shown errors.
    document.getElementById("accordion_error_box").style.display = "none";
}

// Post an form to the request presenter ajax processor. 
// The type of request and presenter should be given in a form value called 'request_presenter'.
// If a value called 'presenter_postback' is present then the processor will try to implement the request, otherwise the presenter will be filled with default values.
// The postParameter is passed on the the success (or failure) handler to control the actions to take post-processing.
function accordionModulePost(formName, index, postParameter) {
    var ajaxUrl = "/ajax/PresenterRequest_Ajax.aspx?mysess=" + getURLParam("mysess") + "&mydate=" + getEpochTime();
    // Post the form data to the ajax page.
    YAHOO.util.Connect.setForm(formName);
    YAHOO.util.Connect.asyncRequest('POST', ajaxUrl, {
        success: accordionModulePostSuccess,
        failure: accordionModulePostFailure,
        argument: { index: index, postParameter: postParameter } 
    });
}

// Ajax success handler for accordionModulePost, dealing with the ajax response from the request presenter ajax processor. 
function accordionModulePostSuccess(ajaxResponse) {
    // The positional index of the module just processed.
    var index = ajaxResponse.argument.index;
    // A parameter passed to control what to do next.
    var postParameter = ajaxResponse.argument.postParameter;

    // The response from the request presenter ajax processor.     
    var responseArray = ajaxResponse.responseText.split("|");
    var presenterHtml = responseArray[1];

    // If the request has been successfully implemented then use the post parameter to control what to do next.
    if (responseArray[0] == "True") {

        var currentUrlArray = new String(window.location).split("/");
        var redirectUrl = currentUrlArray[0] + "//" + currentUrlArray[2] + "/uh_account_details.aspx?mysess=" + getURLParam("mysess") + "&mydate=" + getEpochTime();
        var action = document.getElementById("action_" + index);
        var cancel = document.getElementById("cancel_" + index);

        // If a save and confirm module with pending changes has been processed (i.e. the changes have been discarded and the presenter now contains default values) then keep the module open. 
        if (postParameter == "DiscardChanges") {
		    // Reset presenter display according to ajax response.
		    document.getElementById("dynamic_block_" + index).innerHTML = presenterHtml;
    		// Hide any previously shown errors.
		    document.getElementById("accordion_error_box").style.display = "none";
		    // Change the module's action to say Next and redirect to the confirmation page when clicked		    
		    action.src = "/images/buttons10/g-next-white.png";
		    action.alt = "Next";
		    document.getElementById("postParameter_" + index).value = "EmailConfirm";

        // If pending changes have been created by a save and confirm module or the advertiser's password has been changed, then redirect toa confirmation page.
		} else if ((postParameter == "Password") || (postParameter == "EmailConfirm" && presenterHtml.indexOf("discard_pending_changes") > -1)) {

		    // Reset presenter display according to ajax response.
		    document.getElementById("dynamic_block_" + index).innerHTML = presenterHtml;
		    // Hide any previously shown errors.
		    document.getElementById("accordion_error_box").style.display = "none";

		    // does the presenteHTML contain a confirmation div and if so change the button to ok and refresh the page to reset everything
		    if (!document.getElementById("save_confirmed")) {
		        action.src = "/images/buttons10/g-next-white.png";
		        action.alt = "Next";
		        cancel.style.display = "inline";		        
		        accordionCollapse(index);
		    } else {		    
		        action.src = "/images/buttons10/g-ok-white.png";
		        action.alt = "OK";
		        action.onclick = function() { window.location = redirectUrl; };
		        cancel.style.display = "none";		       
		    }
		// In all other cases just collapse the accordion module.
		} else {
		    // Hide any previously shown errors.
		    document.getElementById("accordion_error_box").style.display = "none";
		    
		    // Reset presenter display according to ajax response.
		    document.getElementById("dynamic_block_" + index).innerHTML = presenterHtml;
		    
		    // does the presenteHTML contain a confirmation div and if so change the button to ok and refresh the page to reset everything
		    if (!document.getElementById("save_confirmed")) {
		        action.src = "/images/buttons10/g-next-white.png";
		        action.alt = "Next";		        
                cancel.style.display = "inline";		        
		        accordionCollapse(index);
		    } else {
		        action.src = "/images/buttons10/g-ok-white.png";
		        action.alt = "OK";
		        action.onclick = function() { window.location = redirectUrl; };
		        cancel.style.display = "none";		        
		    }
		}

	// If the request has failed to validate or the presenter has been filled with default values then keep the module open and display any errors.
	} else {  
	    // Reset presenter display according to ajax response.
	    document.getElementById("dynamic_block_" + index).innerHTML = presenterHtml;

	    // If there are any errors then show them in the error box.
	    if (responseArray.length > 2) {
	        var errors = "<ul>";
	        for (var i = 2; i < responseArray.length; i++) {
	            errors += "<li>" + responseArray[i] + "</li>";
	        }
	        errors += "</ul>";
	        document.getElementById("form_error_header_div").innerHTML = errors;
	        document.getElementById("accordion_error_box").style.display = "block";
	    }
    }
}

// Ajax failure handler for accordionModulePost.
function accordionModulePostFailure(ajaxResponse) {
    // Show a technical error message in the error box.
    document.getElementById("accordion_error_box").innerHTML = "<ul><li>Something went wrong. Please try again.</li></ul>";
    document.getElementById("accordion_error_box").style.display = 'block';    
}

// A horrible hack to manage a last minute spec change. 
// This function is called whenever the varible html blocks in the sms alerts presenter change to change the image and post parameter associated with the Save button.
function smsAlertsSaveConfirmSaveButton() {
    var save = document.getElementById("action_5");
    checkedValue = getCheckedValue(document.getElementsByName("sms_yn"));
    if (checkedValue == "1") {
        save.src = "/images/buttons10/g-next-white.png";
        save.alt = "Next";
        document.getElementById("postParameter_5").value = "EmailConfirm";
    } else {
        save.src = "/images/buttons10/g-save-white.png";
        save.alt = "Save";
        document.getElementById("postParameter_5").value = "";
    }
}


/* Fast Track price calculations */
var ft_selected_items = new Array();

// Pre-select and display totals for previously selected product options on page refresh and on browser back button use
// ** Note: This will work as long as all the price options are check boxes and the id's starts with "price_". **
function fastTrackShowTotalsOnPageLoad() {
	var firstAdChecked = (document.getElementById("price_firstad") && document.getElementById("price_firstad").checked);
	var premAdChecked = (document.getElementById("price_premad") && document.getElementById("price_premad").checked);
	var premAdPlusChecked = (document.getElementById("price_prplus") && document.getElementById("price_prplus").checked);
	var premAdUpChecked = (document.getElementById("price_premup") && document.getElementById("price_premup").checked);
	var premAdPlusUpChecked = (document.getElementById("price_pgup") && document.getElementById("price_pgup").checked);
	
    if (firstAdChecked || premAdChecked || premAdPlusChecked || premAdUpChecked || premAdPlusUpChecked) {
        showMarketingItems(true, true);
    }

    fastTrackReCalculateSelectedOptions();
}

// Show or hide marketing items
function showMarketingItems(show, showCheckboxes) {
    var noProductWarningTexts = YAHOO.util.Dom.getElementsByClassName('no_product_selected');
    var checkboxes = YAHOO.util.Dom.getElementsByClassName('product_option_chkbx');

    toggleVisible(checkboxes, show);
    toggleVisible(noProductWarningTexts, !show);
    if (!showCheckboxes) {
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                checkboxes[i].checked = showCheckboxes
            }
        }
        if (YAHOO.util.Dom.get('pay_freq')) {
            fastTrackReCalculateSelectedOptions();
        } else {
        return;
        }
    }
    

    if (show) {
        if (document.getElementById('ft_marketing_hide')) { document.getElementById('ft_marketing_hide').style.display = 'none'; }

        changeCollapsedState(YAHOO.util.Dom.get('ft_marketing_1'), true);
        changeCollapsedState(YAHOO.util.Dom.get('ft_marketing_2'), true);
        changeCollapsedState(YAHOO.util.Dom.get('ft_marketing_3'), true);
        
		var premAdPlusChecked = (document.getElementById("price_prplus") && document.getElementById("price_prplus").checked);
		var premAdPlusUpChecked = (document.getElementById("price_pgup") && document.getElementById("price_pgup").checked);

        // Show additional text for Spotlights when Premium Plus option selected.
	    if (document.getElementById("prplus_spotlights_text")) {
	        if (premAdPlusChecked || premAdPlusUpChecked) {
	            document.getElementById("prplus_spotlights_text").style.display = 'block';
	        } else {
	            document.getElementById("prplus_spotlights_text").style.display = 'none';
	        }   
	    }

	    // Show additional text for Deals when Premium Plus option selected.
	    if (document.getElementById("prplus_deals_text")) {
	        if (premAdPlusChecked || premAdPlusUpChecked) {
	            document.getElementById("prplus_deals_text").style.display = 'block';
	        } else {
	            document.getElementById("prplus_deals_text").style.display = 'none';
	        }
	    }		
	} else {
	    if (document.getElementById('ft_marketing_hide')) { document.getElementById('ft_marketing_hide').style.display = 'block'; }
	    YAHOO.util.Dom.get("prplus_deals_text").style.display = 'none';
	    YAHOO.util.Dom.get("prplus_spotlights_text").style.display = 'none';

	    changeCollapsedState(YAHOO.util.Dom.get('ft_marketing_1'), false);
	    changeCollapsedState(YAHOO.util.Dom.get('ft_marketing_2'), false);
	    changeCollapsedState(YAHOO.util.Dom.get('ft_marketing_3'), false);
	}
}

function toggleVisible(elems, enabled) {
    for (var i = 0; i < elems.length; i++) {
        elems[i].style.display = (enabled ? 'block' : 'none');
    }
}

// On change of advert type selection
function fastTrackAdvertTypeOnChange(element) {
    var isChecked = element.checked;
    
	// If checked then uncheck all other advert options.
    if (element.checked) {
		if (YAHOO.util.Dom.get("price_premad")) {
			YAHOO.util.Dom.get("price_premad").checked = false;
		}
		
		if (YAHOO.util.Dom.get("price_premup")) {
			YAHOO.util.Dom.get("price_premup").checked = false;
		}
		
		if (YAHOO.util.Dom.get("price_prplus")) {
			YAHOO.util.Dom.get("price_prplus").checked = false;
		}
		
		if (YAHOO.util.Dom.get("price_pgup")) {
			YAHOO.util.Dom.get("price_pgup").checked = false;
		}
		
		if (YAHOO.util.Dom.get("price_firstad")) {
			YAHOO.util.Dom.get("price_firstad").checked = false;
		}

		if (YAHOO.util.Dom.get("price_prem_taster_c")) {
		    YAHOO.util.Dom.get("price_prem_taster_c").checked = false;
		}

		if (YAHOO.util.Dom.get("price_prem_taster")) {
			YAHOO.util.Dom.get("price_prem_taster").checked = false;
		}

		if (YAHOO.util.Dom.get("price_prem_6months")) {
			YAHOO.util.Dom.get("price_prem_6months").checked = false;
		}

		if (YAHOO.util.Dom.get("price_prem_3months")) {
			YAHOO.util.Dom.get("price_prem_3months").checked = false;
		}
	}
    element.checked = isChecked;
	// Determine whether and how to show the additional marketing section.
    showMarketingItems(element.checked || document.getElementById("totalWithoutAdvert").value == 'True', element.checked);

    // The only product allowed on subscription is a new premium advert.
    if ($$("price_premad") && $$("price_premad").checked && !document.getElementById("disc_premium_advert")) {
    	// If we're in annual mode then show the quarterly option.
    	if ($$("pay_freq").value == "annual" && $$("quarterly_option")) {
    		$$("quarterly_option").style.display = "block";
    	}
    } else {
    	// Ensure we're in annual mode, and hide the quarterly option.
    	$$("pay_freq").value = "annual";
    	if ($$("quarterly_option")) {
    		$$("quarterly_option").style.display = "none";
    	}
    }

    // Redisplay, recalculate, and reset the payment totals.
	displayYearlyQuarterly();
}

// On change of paid link selection
function fastTrackPaidLinkOnChange(element) {
    var otherElement;
    if (element.id == "price_link_yes") { otherElement = document.getElementById("price_link_no"); }
    if (element.id == "price_link_no") { otherElement = document.getElementById("price_link_yes"); }

    if (element.checked) {
        if (otherElement.checked) {
            otherElement.checked = false;
        }
    }

    fastTrackReCalculateSelectedOptions();
}

// On change of webcreator selection
function fastTrackWebcreatorOnChange(boxJustClicked) {
    if (boxJustClicked == "price_webyear" && YAHOO.util.Dom.get("price_webset")) {
        document.getElementById("price_webset").checked = document.getElementById("price_webyear").checked;
    }
    if (boxJustClicked == "price_webset") {
        document.getElementById("price_webyear").checked = document.getElementById("price_webset").checked;
    }

    fastTrackReCalculateSelectedOptions();
}

function autoRenewalStateOnChange(sessionId, homeId, reload) {
	fastTrackReCalculateSelectedOptions();
	return autoRenewalChange("price_autornw", sessionId, homeId, reload);
}

function autoRenewalChange(inputId, sessionId, homeId, reload) {
	var autoRenew = document.getElementById(inputId).checked;
	var message;
    var title;
    if (autoRenew) {
        title = 'Confirm your subscription';
        message = 'You have opted for an annual subscription for Home ' + homeId + '.<br /><br />For peace of mind we will always send you reminders before the payment is due and you can cancel at any time.';
	} else {
	    title = 'Are you sure?';
	    message = 'You have opted to manually renew your advert for Home ' + homeId + '.<br /><br />An annual subscription will take away the fuss of renewing each year.  We will always send you reminders and you can cancel any time.<br /><br />Are you sure you want to manually renew your advert?';
	}
	var fn = function (confirmed) {
		if (confirmed) {
			hl.messaging.pleaseWait();
			var action = autoRenew ? "active" : "cancelrenewal",
				surl = "ajax/homes_auto_renewal_ajax.aspx?mysess=" + sessionId + "&home_id=" + homeId + "&action=" + action + "&r=" + Math.random();

			var fnSuccess = function (o) {
				var responseText = o.responseText;
				var responses = responseText.split('|');
				if (responses[0] == "Error") {
					// Give the user a nice, friendly error message instead of the horrific techie one.
					var title = 'Oops, something went wrong!';
					var email = autoRenew ? 'details' : 'advert.cancel';
					var message = 'For some reason your request to ' + (autoRenew ? 'setup' : 'cancel') + ' your subscription failed.<br/><br/>If you still want to change your annual subscription, please email <a href="mailto:' + email + '@holidaylettings.co.uk">' + email + '@holidaylettings.co.uk</a> with the details.';
					hl.messaging.alert(message, title);
				}
				if (reload === true) {
					window.location = window.location.href;
				} else {
					hl.messaging.closeDialogs();
				}
			};
			var fnError = function () {
				hl.messaging.closeDialogs();
				hl.messaging.alert('There was an unspecified problem - please go back to the Home Management page and try again or contact us if the problem persists.');
			};

			YAHOO.util.Connect.asyncRequest('GET', surl, { success: fnSuccess, failure: fnError });
		} else {
			var elem = document.getElementById(inputId);
			elem.checked = !elem.checked;
		}
	};
	hl.messaging.confirm(message, title, fn, 'Confirm', 'Cancel');
    // Return true for now - we'll reset the check box when the user responds to the dialog.
    return true;
}

function autoRenewalSetAll(element) {
    $(element).parents('table').find('input[type=checkbox]').prop('checked', element.checked);
}

// Re-select all selected product options and add it to the list to re-calculate the totals
function fastTrackReCalculateSelectedOptions() {
    ft_selected_items = new Array();
    d = document.forms["continue_form"];
    for (i = 0; i < d.elements.length; i++) {
        if (d.elements[i].type == "checkbox" && d.elements[i].id.indexOf("price_") >= 0 && d.elements[i].checked) {
            ft_selected_items.push(d.elements[i].id);
        }
    }

    fastTrackCalculateTotals();
}

// Reset and re-calculate totals
function fastTrackCalculateTotals() {

    // TODO: move inline styles into external stylesheet
    // (see CollapsiblePaymentPageControllerBase.cs).
    var productRowTemplate = "<table id='PRODUCT_ID_product_row' border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td style='width:740px; padding:2px 0px; text-align:right; font-weight:bold;'><span id='span_PRODUCT_ID'>PRODUCT_DESC</span></td><td style='width:73px; padding:2px 0px; text-align:right; font-weight:bold; padding-right:40px;'>&pound;<span id='span_PRODUCT_ID_price'>PRODUCT_PRICE</span></td></tr></table>";

    // Determine whether we're in quarterly or annual payment mode
    var quarterly = (YAHOO.util.Dom.get('pay_freq').value == 'quarterly');

    // Reset totals
    document.getElementById('hdnVat').value = "0";
    document.getElementById('hdnSbNext').value = "0";
    document.getElementById('hdnSbVat').value = "0";
    document.getElementById('hdnTotal').value = "0";
    document.getElementById('price_vat').innerHTML = "0.00";
    document.getElementById('price_total').innerHTML = "0.00";
    document.getElementById('product_rows').innerHTML = "";
    if (quarterly) {
        document.getElementById('total_SB_now').innerHTML = "0.00";
        document.getElementById('total_SB_next').innerHTML = "0.00";
    }
    var vatRate = document.getElementById('hdnVatRate').value;
    var hdnVat = document.getElementById('hdnVat');
    var hdnTotal = document.getElementById('hdnTotal');
    if (quarterly) {
        var hdnSbNext = $$("hdnSbNext");
        var hdnSbNextVat = $$("hdnSbVat");
    }

    if ((document.getElementById("price_firstad") && document.getElementById("price_firstad").checked) ||
        (document.getElementById("price_premad") && document.getElementById("price_premad").checked) ||
        (document.getElementById("price_pgup") && document.getElementById("price_pgup").checked) ||
        (document.getElementById("price_prplus") && document.getElementById("price_prplus").checked)) {
        $('#head_annualSub').show();
        $('#annualSub').show();
    } else {
        $('#head_annualSub').hide();
        $('#annualSub').hide();
    }

    // Calculate totals only when one of the advert types has been selected
    var productRows = "";
    if (
        (document.getElementById("price_firstad") && document.getElementById("price_firstad").checked) ||
        (document.getElementById("price_premad") && document.getElementById("price_premad").checked) ||
        (document.getElementById("price_prplus") && document.getElementById("price_prplus").checked) ||
        (document.getElementById("price_prem_taster_c") && document.getElementById("price_prem_taster_c").checked) ||
        (document.getElementById("price_prem_taster") && document.getElementById("price_prem_taster").checked) ||
        (document.getElementById("price_prem_3months") && document.getElementById("price_prem_3months").checked) ||
        (document.getElementById("price_prem_6months") && document.getElementById("price_prem_6months").checked) ||
        document.getElementById("totalWithoutAdvert").value == 'True'
        ) {
        for (var index in ft_selected_items) {
            var element = document.getElementById(ft_selected_items[index]);
            var description = '';
            var price = 0;

            if (quarterly && element.getAttribute('hl_descsb') != '' && element.getAttribute('hl_pricesb') > 0) {
                description = element.getAttribute('hl_descsb');
                price = parseFloat(element.getAttribute('hl_pricesb'));
                hdnSbNext.value = parseFloat(hdnSbNext.value) + price;
            } else if (element.getAttribute('hl_desc')) {
                description = element.getAttribute('hl_desc');
                price = parseFloat(element.getAttribute('hl_price'));
            }

            if (description) {
                hdnTotal.value = parseFloat(hdnTotal.value) + price;

                var productRow = productRowTemplate.replace("PRODUCT_DESC", description);
                productRow = productRow.replace("PRODUCT_PRICE", (Math.round(price * 100) / 100).toFixed(2));
                productRow = productRow.replace( /PRODUCT_ID/g , ft_selected_items[index].replace("price_", ""));
                productRows += productRow;
            }
        }

        // Finish off the list of products with a ruled line
        if (productRows != '') {
            productRows += "<hr style='color:#3399ff;background-color:#3399ff'/>";
        }

        if (vatRate < 1) {
            hdnVat.value = Math.round((hdnTotal.value * vatRate * 100).toFixed(2)) / 100;
            if (quarterly) {
                hdnSbNextVat.value = Math.round((hdnSbNext.value * vatRate * 100).toFixed(2)) / 100;
            }
        }

        hdnTotal.value = parseFloat(hdnTotal.value) + parseFloat(hdnVat.value);
        if (quarterly) {
            hdnSbNext.value = parseFloat(hdnSbNext.value) + parseFloat(hdnSbNextVat.value);
        }

        // Display selected product rows with description and price
        document.getElementById('product_rows').innerHTML = productRows;

        // Display VAT
        var displayVatValue = Math.round(parseFloat(hdnVat.value) * 100) / 100;
        document.getElementById('price_vat').innerHTML = displayVatValue.toFixed(2);

        // Display Total
        var displayTotalValue = Math.round(parseFloat(hdnTotal.value) * 100) / 100;
        document.getElementById('price_total').innerHTML = displayTotalValue.toFixed(2);

        // Display quarterly payment prices (initially hidden)
        if (quarterly) {
            var displaySbNowValue = Math.round(parseFloat(hdnTotal.value) * 100) / 100;
            document.getElementById('total_SB_now').innerHTML = displaySbNowValue.toFixed(2);

            var displaySbNextValue = Math.round(parseFloat(hdnSbNext.value) * 100) / 100;
            document.getElementById('total_SB_next').innerHTML = displaySbNextValue.toFixed(2);
        }
    }
}

// Fast Track comparison of adverts table
// Note: The content is rendered towards the end of page, which is then moved under the Triangle popup box's div.
function fastTrackAdvertComparisonPopupShow() {
	document.getElementById('advert_comparison').style.display = 'block';
    createTrianglePopup('advert_comparison', 'advert_comparison_popup', 170, 0, 418, 210, "");
    document.getElementById('triTop_content').appendChild(document.getElementById('advert_comparison_content'));
    document.getElementById('advert_comparison_content').style.display = '';
}

//================================================================================

// Generic data selector control; uses YUI calendar. Loading page should call
// setUpCalendars function and pass the maximum number of date selectors to be
// included on the page.

var calendars = new Array();
var calExists = new Array();
var calShown = new Array();

function setUpCalendars(numDateSelectors) {
	for (var calPos = 0; calPos < numDateSelectors; calPos++) {
		calExists[calPos] = false;
		calShown[calPos] = false;
	}
}

function handleCalendarClick(element_id) {
	var calendar_number = element_id.substr(element_id.lastIndexOf("_") + 1);
	
	if (calShown[calendar_number]) {
		calendars[calendar_number].hide();
		calShown[calendar_number] = false;
	} else {
	    showCalendar(calendar_number);
		calShown[calendar_number] = true;
	}
}

function showCalendar(calendar_number) {
    if (calExists[calendar_number]) {
        // Reset the min and max date properties.
        calendars[calendar_number].cfg.setProperty("mindate", document.getElementById("hdn_date_selector_min_dt_" + calendar_number).value);
        calendars[calendar_number].cfg.setProperty("maxdate", document.getElementById("hdn_date_selector_max_dt_" + calendar_number).value);
        setCalendarDate(calendars[calendar_number], calendar_number);
		calendars[calendar_number].show();
	}
	else {
	    var conf = getCalendarData(calendar_number);
		
		calendars[calendar_number] = new YAHOO.widget.Calendar('cal' + calendar_number, 'cal' + calendar_number + 'Contain', {
			mindate:document.getElementById("hdn_date_selector_min_dt_" + calendar_number).value,
			maxdate:document.getElementById("hdn_date_selector_max_dt_" + calendar_number).value,
			title:"Choose&nbsp;a&nbsp;date:",
			selected:conf[0],
			pagedate:conf[1]
		});
		
		var calArray = new Array(2);
		calArray[0] = calendar_number;
		calArray[1] = calendar_number;
		calendars[calendar_number].selectEvent.subscribe(dateSelected, calArray);
		calendars[calendar_number].render();
		calendars[calendar_number].show();
		calExists[calendar_number] = true;
	}
}

function setCalendarDate(calendar, calendar_number) {
    var ym_data = getCalendarData(calendar_number);
	calendar.select(ym_data[0]);
	calendar.cfg.setProperty("pagedate", ym_data[1]);
	calendar.render();
}

// Gets the date currently entered via the text boxes and select list. 
function getCalendarData(calendar_number) {
    var dt = new Date();
    
	var day = document.getElementById('txt_datesel_day_' + calendar_number).value;
	if (day == '' || isNaN(day)) { day = dt.getDate(); }

	var month = document.getElementById('sel_datesel_month_' + calendar_number).value;
	if (month == '' || isNaN(month)) { month = dt.getMonth() + 1; }

	var year = document.getElementById('txt_datesel_year_' + calendar_number).value;
	if (year == '' || isNaN(year)) { year = dt.getFullYear(); }

	var calData = [];
	calData[0] = month + "/" + day + "/" + year;
	calData[1] = month + "/" + year;
	
	return calData;
}

var dateSelected = function(type, args, obj) {
    var dates = args[0];
    var date = dates[0];
    updateTextField(date, obj[0]);
    calendars[obj[1]].hide();
    calShown[obj[1]] = false;
}

function updateTextField(date, calendar_number) {
    var day = date[2].toString();

	var month = date[1].toString();
	
	var year = date[0].toString();

	document.getElementById("txt_datesel_day_" + calendar_number).value = day;
	document.getElementById("sel_datesel_month_" + calendar_number).selectedIndex = month - 1;
	document.getElementById("txt_datesel_year_" + calendar_number).value = year;

	// Call the onchange event of the month select list (if any) in case anything further should happen when a date is selected.
	if (YAHOO.util.Dom.get("sel_datesel_month_" + calendar_number).onchange) {
	    YAHOO.util.Dom.get("sel_datesel_month_" + calendar_number).onchange();
	}
}

//================================================================================

// Generic picture chooser control

function selectSpotlightPhoto(photoId, picPath) {
	document.getElementById("hdn_picture_chooser").value = photoId;
	document.getElementById("spot_photo").style.background = "url(" + picPath + ")";
	YAHOO.picChooserLightBox.dialog.hide();	
}

// Initialise the lightbox used by the pic selector.
function initPicChooser() {
    if (document.getElementById("div_pc_lightbox") != null) {
        YAHOO.picChooserLightBox.dialog = new YAHOO.widget.Dialog("div_pc_lightbox",
					{ width: "740px", fixedcenter: true, visible: false, draggable: true, modal: true, close: true, constraintoviewport: true });
        YAHOO.picChooserLightBox.dialog.render();
    }
}

//================================================================================

// This is a function specific to the add spotlight page. It is called when the user changes the number of weeks they want for their spotlight.
// Each parameter is expected to be an array with an element for each possible value of the spot type dropdown list (3 values, so indexes 0, 1, and 2).
// The first parameter's values should be dates in the form 'dd/mm/yyyy' and reset the calendar's hidden max date.
// The second parameter's values should be boolean true/false, and reset the save button's src attribute.
function changeSpotType(maxDt, useCredit) {

    var dateMax = document.getElementById('hdn_date_selector_max_dt_0');
    if (dateMax != null) {
        dateMax.value = maxDt[document.getElementById('spot_product').selectedIndex];
    }

    var saveButton = document.getElementById('spot_save');
    if (saveButton != null) {
        if (useCredit[document.getElementById('spot_product').selectedIndex]) {
            saveButton.setAttribute('src', 'images/buttons10/g-use-credit-white.png');
        } else {
            saveButton.setAttribute('src', 'images/buttons10/g-make-a-payment-white.png');
        }
    }
}

var usePopUp = true;

function disableNavigateAwayPopUp() {
    usePopUp = false;
}

function enableNavigateAwayPopUp() {
    usePopUp = true;
}

function navigateAwayAlert(e) {
    if (usePopUp) {
        var message = "To log into your account next time, use the 'Login / Register' link on the left hand side of the site, or via the link in the welcome email we sent you.";

        if (!e) {
            e = window.event;
        }

        if (e) {
            e.returnValue = message;
        }

        return message;
    }
}

function setFtEventListeners(continueIds) {
    //Id log_out is defined in the advertiser styles design kit, so that won't change throughout the process
    YAHOO.util.Event.on(YAHOO.util.Dom.get('log_out'), 'click', function(e) {
        disableNavigateAwayPopUp();
    });

    //Iterate over the elements we wantt o make exempt for the popup
    for (var i = 0; i < continueIds.length; i++) {
        YAHOO.util.Event.on(YAHOO.util.Dom.get(continueIds[i]), 'click', function(e) {
            disableNavigateAwayPopUp();
        });
    }
}

function warnAboutLeavingFt(continueIds) {
    continueIds = (continueIds ? continueIds : new Array('continue'));

    YAHOO.util.Event.addListener(window, 'beforeunload', function(e) {
            return navigateAwayAlert(e);        
        }
    );

    YAHOO.util.Event.addListener(window, 'load', function(e) {
            setFtEventListeners(continueIds);
        }
    );
}

function togglePromocodeInfoText() {
    var promoInfoText = YAHOO.util.Dom.get('ft_promo_helptext');
    var promoInputText = YAHOO.util.Dom.get('aff_id');
    if (promoInputText.value == "") {
        promoInfoText.style.visibility = 'hidden';
    } else {
        promoInfoText.style.visibility = 'visible';
    }
    return true;
}

function calculateBathrooms() {
	if (YAHOO.util.Dom.get('spn_total_bathrooms')) {
		var bathrooms = parseInt(YAHOO.util.Dom.get('hom_bathrooms').value);
		var enSuites = parseInt(YAHOO.util.Dom.get('hom_num_ensuite').value);
	    var showerRooms = parseInt(YAHOO.util.Dom.get('hom_shower_rooms').value);
		var totalBathrooms = bathrooms + enSuites + showerRooms;
		
		// Set span text and hidden form field value
		YAHOO.util.Dom.get('spn_total_bathrooms').innerHTML =  totalBathrooms;
		YAHOO.util.Dom.get('hdn_hom_total_bathrooms').value = totalBathrooms;
	}
}

function onChangeOfferFilterType() {
	if (document.getElementById('offer_filter').selectedIndex == 0) {
		document.getElementById('offer_filter_text').style.display = "none";
	} else {
		document.getElementById('offer_filter_text').innerHTML =
						"<p><b>Note:</b> If your home has not got the <b>'" +
						document.getElementById('offer_filter').options[document.getElementById('offer_filter').selectedIndex].text +
						"'</b> option enabled, then it will be automatically added when activating this deal.</p>";
		document.getElementById('offer_filter_text').style.display = "block";
	}
}

if (typeof hl == 'undefined') {
    hl = { };
}
hl.messaging = (function () {
	var baseMsgBox = function (params) {
		if ($('.modal_dialog_mask').length > 0) {
			return -1;
		}
		var element = document.createElement('div');
		element.setAttribute('id', 'modal-dialog-container');
		var mask = document.createElement('div');
		$(mask).addClass('modal_dialog_mask');
		element.appendChild(mask);
		var dialog = document.createElement('div');
		$(dialog).addClass('modaldialog');
		element.appendChild(dialog);
		if (params.title) {
			var title = document.createElement('span');
			$(title).addClass('title');
			title.innerHTML = params.title;
			dialog.appendChild(title);
		}
		var span = document.createElement('span');
		span.innerHTML = params.message;
		dialog.appendChild(span);
		// Step backwards through the buttons, as they're floated right.
		for (var idx = params.buttons.length - 1; idx >= 0; --idx) {
			var btn = params.buttons[idx];
			var input = addButton(btn.text, btn.value, element, params.callback);
			dialog.appendChild(input);
		}
		document.body.appendChild(element);
		return 1;
	};

	var addButton = function (text, value, element, callback) {
		var input = document.createElement('input');
		input.type = 'button';
		input.value = text;
		input.onclick = function () { document.body.removeChild(element); if (callback) callback(value); };
		return input;
	};

	var obj = {};
	obj.confirm = function (message, title, callback, okText, cancelText) {
		var params = {};
		if (message) { params.message = message; }
		if (title) { params.title = title; }
		if (callback) { params.callback = callback; }
		if (!okText) { okText = "OK"; };
		if (!cancelText) { cancelText = "Cancel"; };
		params.buttons = [{ text: okText, value: true }, { text: cancelText, value: false}];
		return baseMsgBox(params);
	};
	obj.alert = function (message, title, okText) {
		var params = {};
		params.message = message;
		params.title = title;
		if (okText == null) {
			okText = "OK";
		}
		params.buttons = [{ text: okText}];
		return baseMsgBox(params);
	};
	obj.pleaseWait = function () {
		return baseMsgBox({ title: "Please wait...", message: "<img src='/images/ajax_busy.gif' />", buttons: [] });
	};
	obj.closeDialogs = function () {
		$('#modal-dialog-container').remove();
	}
	return obj;
})();

