/* ------------------ PAYMENTS ------------------------ */

/* 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;
}

/* 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 = 1.15;
	}
	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);
}

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;
}

/* 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('-ofrcred')) {
		document.getElementById('-ofrcred').disabled = false;
		YAHOO.util.Dom.removeClass('-ofrcredlabel', '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");
	
	if (classic.checked || premium.checked) {
		allow_extras(home_id);
	} else {
		disallow_extra(home_id + '-link');
		disallow_extra(home_id + '-spot3');
		disallow_extra(home_id + '-spot6');
		
		// Disable Other Products only if there are no active homes
		// (applies more to multi-home payments).
		if (document.getElementById('hdn_active_adverts').value == 0) {
			disallow_extra('-ofrcred');
			disallow_extra(home_id + '-webcreatornew');
			disallow_extra(home_id + '-webyear');
		}
	}
}

/* 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 == "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 = pr_extraSB;
                    } else {
                        price = re_extraad;
                        priceSB = re_extraSB;
                    }
					
                } else if (type == "pr") {
					// Premium Advert - determine whether to use activation or
					// renewal price
                    if (action == "activate") {
                        price = pr_xpremad;
                        priceSB = 0;
                    } else {
                        price = re_xpremad;
                        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 otherElement;
	var activeAdverts = document.getElementById('hdn_active_adverts').value;
	
	if (element.id == classic) { otherElement = document.getElementById(premium); }
	if (element.id == premium) { otherElement = document.getElementById(classic); }
	
	if (element.checked) {
		if (otherElement.checked == true) {
			otherElement.checked = false;
			single_change(otherElement);
		} else {
			if (element.id == classic || element.id == premium) { activeAdverts++; }  // Add one to tally of active adverts
		}
	} else {
		if (element.id == classic || element.id == premium) { 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.
	//----------------------------------------------------------------------------
	
	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, "link");
    } else {
		disableOption(colo_parent_id, "groupad");
		disableOption(colo_parent_id, "spot3");
		disableOption(colo_parent_id, "spot6");
		disableOption(colo_parent_id, "link");
    }
}

//================================================================================

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 transcation 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 start_payments() {
	
	var objPayFreq;
	
	if (objPayFreq = document.getElementById('pay_freq')) {  // Check for existence of pay_freq field
		if (objPayFreq.value == 'quarter') { go_quarterly(); }
		update_total();
	}

}

// **************************************************** 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 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', 'visibility', 'visible');
}

function handle_pic_swap(o) {
	var result = o.responseText;
	
	var updates = result.split('|');
	
	//Change photos
	document.getElementById('pic' + updates[0]).src = updates[1];
	document.getElementById('pic' + updates[2]).src = updates[3];
	
	//Alter orientations
	var pic1 = document.getElementById('box' + updates[0]);
	var pic2 = document.getElementById('box' + updates[2]);
	var temp = pic1.getAttribute('hl_orient');
	pic1.setAttribute('hl_orient', pic2.getAttribute('hl_orient'));
	pic2.setAttribute('hl_orient', temp);
	
	// 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=' + new Date().getTime();
		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); }

}


/* Functions from uh_owner.js */

/* Contains Ajax Functions For the new signup process */

function RePopDrop() {
    //The user has changed the how found option we need to pass the selected value to the ajax page.
    //Note this action does not require login as it does not affect data and it is possible to be 
    //On stage four without a session if we are recovering a previous signup.
    document.getElementById('how_you_found_us').disabled = true;
    if (document.getElementById('how_found2') != undefined) {
        document.getElementById('how_found2').disabled = true;
    }
    YAHOO.util.Connect.setForm('owner_details');
    var selURL = "uh_owner_ajax.aspx?action=re_pop_drop&ts=" + Date();
    var selReq = YAHOO.util.Connect.asyncRequest('POST', selURL, { success: handleRePopSuccess, failure: HFFailure });
}

function handleRePopSuccess(o) {
    //We have a return from our function.
    if (o.responseText !== undefined) {
        var resArray = o.responseText.split('|', 6);
        if (resArray[0] == "OK") {
            document.getElementById('hfHolder1').innerHTML = "<span style='" + resArray[1] +
				"'>" + resArray[2].replace('&#0124;', '|') + "</span>";
            document.getElementById('hfHolder2').innerHTML = resArray[3].replace('&#0124;', '|');
            document.getElementById('hfHolder4').innerHTML = resArray[5].replace('&#0124;', '|');

        } else {
            //We have nothing to replace with so do nothing for now.
            document.getElementById('how_you_found_us').disabled = false;
            if (document.getElementById('how_found2') != undefined) {
                document.getElementById('how_found2').disabled = false;
            }
        }
    } else {
        //We have nothing to replace with so do nothing for now.
        document.getElementById('how_you_found_us').disabled = false;
        if (document.getElementById('how_found2') != undefined) {
            document.getElementById('how_found2').disabled = false;
        }
    }
}

function HFFailure(o) {
    //Nothing for now.
    document.getElementById('how_you_found_us').disabled = false;
    if (document.getElementById('how_found2') != undefined) {
        document.getElementById('how_found2').disabled = false;
    }
}

function moveToText() {
    //If the owner select an option in how_found 2 we need to move the value to the how_you_found_us field so it will be saved
    //If we'd like them to type more (when the value contains 'please' or '?') then we need to make the field visible and prompt them to type
    var howFound2 = document.getElementById('how_found2');
    var howYouFoundUs = document.getElementById('how_you_found_us');
    var promo = document.getElementById('aff_id');

    var selectedItem = howFound2.options[howFound2.selectedIndex].value;
    if (selectedItem.indexOf('Please') > -1 || selectedItem.indexOf('?') > -1) {
        howYouFoundUs.style.visibility = 'visible'
        howYouFoundUs.value = selectedItem;  //setting the value works better here after setting the type
        howYouFoundUs.focus();
        howYouFoundUs.select();
    } else {
        howYouFoundUs.style.visibility = 'hidden'
        howYouFoundUs.value = selectedItem;  //setting the value works better here after setting the type
        promo.focus();
    }
}

function newTaxCountry() {
    //The user has changed the country they are tax resident in.
    //Note this action does not require login as it does not affect data and it is possible to be 
    //On stage three without a session if we are recovering a previous signup.
    if (document.getElementById('vat_number') != undefined) {
        document.getElementById('vat_number').disabled = true;
    }
    if (document.getElementById('vat_registered_yn') != undefined) {
        document.getElementById('vat_registered_yn').disabled = true;
    }

    YAHOO.util.Connect.setForm('owner_details');

    var couURL = "uh_owner_ajax.aspx?action=new_tax_country&ts=" + Date();
    var couReq = YAHOO.util.Connect.asyncRequest('POST', couURL, { success: handleNewCountrySuccess, failure: NewCountryFailure });
}

function newVATStatus() {
    //The user has changed the country they are tax resident in.
    //Note this action does not require login as it does not affect data and it is possible to be 
    //On stage three without a session if we are recovering a previous signup.
    if (document.getElementById('vat_number') != undefined) {
        document.getElementById('vat_number').disabled = true;
    }

    YAHOO.util.Connect.setForm('owner_details');

    var couURL = "uh_owner_ajax.aspx?action=new_vat_status&ts=" + Date();
    var couReq = YAHOO.util.Connect.asyncRequest('POST', couURL, { success: handleVATSuccess, failure: VATFailure });
}

function handleNewCountrySuccess(o) {
    //We have a return from our function.
    if (o.responseText !== undefined) {
        var resArray = o.responseText.split('|', 3);
        if (resArray[0] == "OK") {
            document.getElementById('vatHolder1').innerHTML = resArray[1].replace('&#0124;', '|');
            document.getElementById('vatHolder2').innerHTML = resArray[2].replace('&#0124;', '|');
            document.getElementById('vatHolder3').innerHTML = "";
            document.getElementById('vatHolder4').innerHTML = "";

        } else {
            //We have nothing to replace with so do nothing for now.
            if (document.getElementById('vat_number') != undefined) {
                document.getElementById('vat_number').disabled = false;
            }
            if (document.getElementById('vat_registered_yn') != undefined) {
                document.getElementById('vat_registered_yn').disabled = false;
            }
        }
    } else {
        //We have nothing to replace with so do nothing for now.
        if (document.getElementById('vat_number') != undefined) {
            document.getElementById('vat_number').disabled = false;
        }
        if (document.getElementById('vat_registered_yn') != undefined) {
            document.getElementById('vat_registered_yn').disabled = false;
        }
    }
}

function handleVATSuccess(o) {
    //We have a return from our function.
    if (o.responseText !== undefined) {
        var resArray = o.responseText.split('|', 5);
        if (resArray[0] == "OK") {
            document.getElementById('vatHolder3').innerHTML = resArray[3].replace('&#0124;', '|');
            document.getElementById('vatHolder4').innerHTML = resArray[4].replace('&#0124;', '|');

        } else {
            //We have nothing to replace with so do nothing for now.
            if (document.getElementById('vat_number') != undefined) {
                document.getElementById('vat_number').disabled = false;
            }
            if (document.getElementById('vat_registered_yn') != undefined) {
                document.getElementById('vat_registered_yn').disabled = false;
            }
        }
    } else {
        //We have nothing to replace with so do nothing for now.
        if (document.getElementById('vat_number') != undefined) {
            document.getElementById('vat_number').disabled = false;
        }
        if (document.getElementById('vat_registered_yn') != undefined) {
            document.getElementById('vat_registered_yn').disabled = false;
        }
    }
}

function NewCountryFailure(o) {
    if (document.getElementById('vat_registered_yn') != undefined) {
        document.getElementById('vat_registered_yn').disabled = false;
    }
    if (document.getElementById('vat_number') != undefined) {
        document.getElementById('vat_number').disabled = false;
    }
}

function VATFailure(o) {
    //We have nothing to replace with so do nothing for now.
    if (document.getElementById('vat_number') != undefined) {
        document.getElementById('vat_number').disabled = false;
    }
    if (document.getElementById('vat_registered_yn') != undefined) {
        document.getElementById('vat_registered_yn').disabled = false;
    }
}


//This function allows the user to switch between the tabs on the settings page. It causes the data on the current
//Tab to be validated and saved before moving on
function ValidateOwnerDetails(mysess, targetTab) {
    YAHOO.util.Connect.setForm('owner_details');
    var valURL = "uh_owner_ajax.aspx?action=validate&data1=" + mysess + "&data2=" + targetTab + "&ts=" + Date();
    var valReq = YAHOO.util.Connect.asyncRequest('POST', valURL, { success: handleValidationSuccess, failure: ValidationFailure });
}

//virtually identical function to call a very similar success event handler that, however, redirects
//to the semi-independent "change password" page, rather than back to the main owner details page
function ValidatePass(mysess, targetTab) {
    YAHOO.util.Connect.setForm('owner_details');
    var valURL = "uh_owner_ajax.aspx?action=validate&data1=" + mysess + "&data2=" + targetTab + "&ts=" + Date();
    var valReq = YAHOO.util.Connect.asyncRequest('POST', valURL, { success: handlePassValidationSuccess, failure: ValidationFailure });
}

function handleValidationSuccess(o) {
	var resArray, targetURL;
    if (o.responseText !== undefined) {
        resArray = o.responseText.split('|', 4);
		targetURL = "uh_owner.aspx?";
        if (resArray[0] == "OK") {
            targetURL += "mysess=" + resArray[3];
            if (resArray[2].length > 0) {
                targetURL += "&e=" + resArray[2];
            }
            targetURL += "&tab=" + resArray[1];
            targetURL += "&ts=" + Date();
            window.location = targetURL;
        } else {
			if (resArray[1] == "SESSION_TIMEOUT") {
				targetURL += "mysess=" + resArray[2];
				window.location = targetURL;
			} else {
	            //We have nothing to replace with so do nothing for now.
	            document.write(resArray[0] + ' : ' + resArray[1]);
			}
        }
    } else {
        ValidationFailure(o);
    }
}

function handlePassValidationSuccess(o) {
    if (o.responseText !== undefined) {
        var resArray = o.responseText.split('|', 4);
        if (resArray[0] == "OK") {
            if (resArray[2] !== "0") {
                var targetURL = "uh_owner.aspx?mysess=" + resArray[3];
            } else {
                var targetURL = "uh_changepassword.aspx?mysess=" + resArray[3];
            }
            if (resArray[2].length > 0) {
                targetURL += "&e=" + resArray[2];
            }
            targetURL += "&tab=" + resArray[1];
            targetURL += "&ts=" + Date();
            window.location = targetURL;
        } else {
            //We have nothing to replace with so do nothing for now.
            document.write(resArray[0] + ' : ' + resArray[1]);
        }
    } else {
        ValidationFailure(o);
    }
}

function ValidationFailure(o) {
    var ajaxError = document.getElementById("ajaxErrorDiv");
    if (ajaxError != null) { ajaxError.style.display = "block"; }
}


//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();
	
}
