$(document).ready(function(){
    portalPicker();
    selectMenu();
    pricingDescriptions();
    previewImage();
    triggerCloseModalWindow();
    addDomain();
    oddlistsandtables();
    autoSubmit();
    confirmDelete();
    confirmSetup();
    //menuHover();
    updatecommitment();
    
    $('input.isdate').datepicker({ dateFormat: 'dd/mm/yy' });
    updateINP();
    
    // -- Opal --
    addressesForm();
    appointmentsForm();
    getAvailableAppointments();
    bookAppointment();
    acceptAddress();
	makeDatePickers();
	siteLocalityChanges();
	updateDirectoryDetails();
    
    // -- Cerb --
    if($('input[name="neworder"]').val() == 'true') neworder();
});

function updateINP(){
	if(($('input[name="snr_hidden"]').val() == '0') || ($('input[name="inp_hidden"]').val() == '0')){
		var url = 'http://www.broadbandfirst.co.uk/ajax.php?do=checkinpsnr&uniqueid=' + $('input[name="id"]').val();
		$('select[name="snr"], select[name="inp"]').after('<img src="/images/loading.gif" alt="Loading..." class="loading"');
		$.getJSON(url, function(json){
			$('select[name="snr"], select[name="inp"]').find('options').removeAttr('selected');
			$('select[name="snr"]').find('option[value="' + json.Pra_SNR_NetConnectCode + '"]').attr('selected', 'selected');
			$('select[name="inp"]').find('option[value="' + json.Pra_INP_NetConnectCode + '"]').attr('selected', 'selected');
			$('img.loading').remove();
		});

	}
}

function updateDirectoryDetails(){
	$('input.Title, input.InitialsForenames, input.NameHeader, input.BusinessSuffix').blur(function(){
		switch($(this).attr('class')){
			case 'Title':
				if($('input.DirectoryEntryTitle').val() == '') $('input.DirectoryEntryTitle').val($(this).val());
			break;
			case 'InitialsForenames':
				if($('input.DirectoryEntryInitialsForenames').val() == '') $('input.DirectoryEntryInitialsForenames').val($(this).val());
			break;
			case 'NameHeader':
				if($('input.DirectoryEntryNameHeader').val() == '') $('input.DirectoryEntryNameHeader').val($(this).val());
			break;
			case 'BusinessSuffix':
				if($('input.DirectoryEntryBusinessSuffix').val() == '') $('input.DirectoryEntryBusinessSuffix').val($(this).val());
			break;
		}
	});
}

function makeDatePickers(){
	var datesArray = ['options[4]', 'options[75]', 'options[77]', 'options[102]', 'options[117]'];
	$.each(datesArray, function(){
		$('input[name="'+this+'"]').datepicker({ dateFormat: 'yy-mm-dd' })
	});
}

function orderAccepted(orderID, orderStatus){
	$('li.orderid').html("OrderID - " + orderID);
	$('li.state').html("Current Order Status - " + orderStatus);
	formSwitch('neworderform', 'ordercomplete');
}

function getFormSerialised(form, methodName){
	$(form).append('<input type="hidden" name="method" value="' + methodName + '" />');
	return $(form).serialize();
}

function addressesForm(){
	$('li.SitePremises input').focus(function(){
		if($('form.AddressForm').length == 0){
			openModalWindow('');
			$.getJSON("http://www.broadbandfirst.co.uk/ajax.php?method=getAddressForm", function(data){
				switch(data.Response){
					case "Success":
						$('#modalbox').append('<form action="" method="" class="AddressForm">' + data.Result + '</form>');
						$('#modalbox form li:first input, #modalbox form li:first select').focus();
						getAvailableAddresses();
					break;
					default:
						alert('Error code #101 occurred, please contact support.');
					break;
				}
			});
			return false
		}
	});
}

function outputErrors(parent, errors){
	//alert(errors);
	$(parent).prepend('<ul id="errors"></ul>');
	if(jQuery.isArray(errors)){
		$.each(errors, function(i, item){
			$('#errors').append('<li>' + item.Errors + '</li>');
		});
	} else $('#errors').append('<li>' + errors + '</li>');
}

function getAvailableAddresses(form){
	$('ul.GetAvailableAddresses button').live('click', function(){
		$(this).after('<img class="loading" src="/images/loading.gif" alt="Loading..." />');
		var formData = getFormSerialised($(this).closest('form'), "getavailableaddresses");
		//alert(formData);
		var errors;
		$.getJSON("http://www.broadbandfirst.co.uk/ajax.php", formData, function(data){
			switch(data.Response){
				case "Validation":
					outputErrors($(this).closest('form'), data.Errors);
				break;
				case "Failed":
					if(data.Errors == 'AMWS2056') alert('No Addresses could be found using your criteria.');
				break;
				case "Good":
					$('#modalbox').empty().append('<form action="" method="post"><ul><li><label>Address</label><select name="address_alk"></select></li><li><label>&nbsp;</label><button name="submit_alk">Add to Order</button></li></ul></form>');
					$.each(data.Addresses, function(i, item){
						$('select[name="address_alk"]').append('<option value="' + item.Address.OrganisationName + '#|#' + item.Address.SubBuilding + '#|#' + item.Address.BuildingName + '#|#' + item.Address.BuildingNumber + '#|#' + item.Address.DependantThoroughfare + '#|#' + item.Address.Street + '#|#' + item.Address.Locality + '#|#' + item.Address.PostTown + '#|#' + item.Address.County + '#|#' + item.Address.PostCode + '#|#' + item.Address.ALK + '#|#' + item.Address.CSSDistrictCode + '#|#' + item.Address.Qualifier + '">'+item.Address.BuildingNumber + " " + item.Address.Street + ", " + item.Address.PostCode + '</option>');
					});
					acceptAddress();
				break;
				default:
					alert(errorHandler(data.Error));
				break;
			}
			$('img.loading').remove();
		});
		return false;
	});
}

function getAvailableAppointments(){
	$('form.appointing button:not(button[name="submit_appointment"])').live('click', function(){
		$(this).after('<img class="loading" src="/images/loading.gif" alt="Loading..." />');
		var formData = getFormSerialised($(this).closest('form'), "getavailableappointments");
		//alert(formData);
		$.getJSON("http://www.broadbandfirst.co.uk/ajax.php", formData, function(data){
			switch(data.Response){
				case "Good":
					$('form.appointing ul li:last').before('<li><label>Appointment</label><select class="AppointmentID" name="' + $('input.AppointmentID').attr('name') + '"></select></label>');
					$('form.appointing input[name="method"]').remove();
					$.each(data.Appointments, function(i, item){
						$('select.AppointmentID').append('<option value="'+item.Appointment.OrigDate+' | '+item.Appointment.TimeSlot+'">'+item.Appointment.Date+" " + item.Appointment.TimeSlot + '</option>');
					});
					$('form.appointing button:not(button[name="submit_appointment"])').attr('name', 'submit_appointment').html('Book Appointment');
				break;
				default:
					outputErrors($(this).closest('form'), data.Errors);
				break;
			}
			$('img.loading').remove();
		});
		return false;
	});
}

function bookAppointment(){
	$('button[name="submit_appointment"]').live('click', function(){
		$(this).after('<img class="loading" src="/images/loading.gif" alt="Loading..." />');
		setAppointmentDateTime();
		var errorContainer = $('ul.newordererrors');
		var formData = getFormSerialised($(this).closest('form'), "bookappointment");
		//alert(formData);
		$.getJSON("http://www.broadbandfirst.co.uk/ajax.php", formData, function(data){
			switch(data.Response){	
				case "Good":
					$('input.AppointmentID').val(data.ReserveAppointment.Appointment.ID);
					$('input.CustomerRequiredByDate, input.CustomerAgreedDate').val(data.ReserveAppointment.Appointment.Date);
					closeModalWindow();
				break;
				default:
					$(this).closest('form').css('border', '1px solid #000');
					outputErrors($('#modalbox'), data.Errors);
				break;	
			}
			$('img.loading').remove();
		});
		return false;
		
	});
}

function appointmentsForm(){
	$('li.CustomerAgreedDate input').focus(function(){
		if($('form.appointing').length == 0){
			openModalWindow('');
			$.getJSON("http://www.broadbandfirst.co.uk/ajax.php?method=getAppointingForm", function(data){
				switch(data.Response){
					case "Success":
						$('#modalbox').append('<form action="" method="post" class="appointing">' + data.Result + '</form>');
						$('#modalbox input.ALK').val($('input.ALK:not(#modalbox input.ALK)').val());
						$('#modalbox input.CSSDistrictCode').val($('input.CSSDistrictCode:not(#modalbox input.CSSDistrictCode)').val());
						var now = new Date;
						$('#modalbox input.EarliestAppointmentDate').val((now.getYear()+1900) + '-' + strPad(now.getMonth()+1,2) + '-' + now.getDate());
						$('#modalbox input.EarliestAppointmentDate').datepicker({ dateFormat: 'yy-mm-dd', minDate: 0})
						$('#modalbox form li:first input, #modalbox form li:first select').focus();
						getAvailableAppointments();
					break;
					default:
						outputErrors($(this).closest('form'), data.Errors);
					break;
				}
			});
			return false
		}
	});
}

function setAppointmentDateTime(){
	var value = $('select.AppointmentID').val().split("|");
	$('input.AppointmentTimeSlot').val(value[1]);
	
	/*
alert("Debug data set in javascript.js see function setAppointmentDateTime. Code needs to be altered to work in live environment")
	// DEBUG - Remove this when live. - the dates provided by the getappointments are dated 2007 - this results in a error when you try to book an appointment.
	// a date mut be in the future. 
	value[0] = '2010-08-10';
*/
	
	$('input.AppointmentDate').val(value[0]);
}

function acceptAddress(){
	$('button[name="submit_alk"]').live('click', function(){
		// Update the address further down the form.
		setSiteDetails($('select[name="address_alk"]').val().split("#|#"));
		closeModalWindow();
		return false;
	});
}

/**
 * This will update the siteLocality and Postcode on the main order
 * form with that looked up on the addresslookup form.
 * @param {Array} address
 */
function setSiteDetails(address){
	
	/**
	 * 0 orgname
	 * 1 subbuilding
	 * 2 buildingname
	 * 3 building num
	 * 4 dependant throughfare
	 * 5 street
	 * 6 locality
	 * 7 posttown
	 * 8 county
	 * 9 postcode
	 * 10 alk
	 * 11 cssd
	 */
	var premises;
	if((address[3] != 'null') && (address[4] != 'null')) premises = address[3] + ' ' + address[4];
	else if(address[3]) premises = address[3];
	else if(address[4]) premises = address[4];
	setOptionValue(new Array('SitePremises', 'DirectoryEntryPremises'), premises) // premises
	setOptionValue(new Array('SiteThoroughfare', 'DirectoryEntryThoroughfare'), address[5]) // Throughfare
	setOptionValue(new Array('SiteLocality', 'DirectoryEntryLocality'), address[6]); // Locality
	setOptionValue(new Array('SitePostcode', 'DirectoryEntryPostcode'), address[9]); // Post Code
	
	setOptionValue(new Array('ALK'), address[10]); // ALK
	
	$('input.ALK').closest('form').append('<input type="hidden" class="CSSDistrictCode" name="CSSDistrictCode" value="' + address[11] + '" />'); // CSSD
}

function setOptionValue(optionId, value){
	$.each(optionId, function(i, id){
		$('input.'+ id).val(value);
	});
	
}

function getOptionID(option){
	var temp = option.split("[");
	temp = temp[1].split("]")
	return temp[0];	
}


/**
 * If these optins change, copy the change elsewhere. 
 */
function siteLocalityChanges(){
	var siteOptions = {'7':'62', '8':'63', '9':'64', '10':'66', '11':'68', '12':'69', '13':'70', '14':'71'};
	$('input[name^="options"]').blur(function(){
		currentId = getOptionID($(this).attr("name"));
		if(currentId in siteOptions){
			//console.log(currentId + " was changed");
			duplicateOptionValue(currentId, siteOptions[currentId]);
		}
	});
}

/**
 * This will copy the value from on option to another - used to duplicate
 * address details and directory entry.
 * @param {Integer} originOptionId
 * @param {Integer} targetOptionId
 */
function duplicateOptionValue(originOptionId, targetOptionId){
	var target = $('input[name="options['+targetOptionId+']"]').val();
	var origin = $('input[name="options['+originOptionId+']"]').val();
	if(!target.match(/^.{1,}$/)) {
		$('input[name="options['+targetOptionId+']"]').val(origin);
	}
}

function formSwitch(rollUp, rollDown){
	$('div.'+rollUp).slideUp();
	$('div.'+rollDown).slideDown();
}

function newAppointment(){
	$('div.appointmentform').hide();
}

function errorHandler(errorString){
	//AMWS1000
	var errorCode = errorString.substring(0, 8);
	var errorMessage = errorString.substring(8);
	var msg = "Unknown error" + errorCode;
	switch(errorCode){
		case 'AMWS1000':
			msg = 'Invalid syntax for field ' + errorMessage;
			break;
		case 'AMWS1001':
			msg = 'Required field ' + errorMessage;
			break;
		case 'AMWS1002':
			msg = 'Invalid combination of data supplied, please remove or add details';
			break;
		case 'AMWS2056':
			msg = 'No matching address found.';
			break;
		case 'AMWS2068':
			msg = 'No address data has been found for that Address Reference';
			break;
		case 'APWS1000':
			msg = "Invalid format for field " + errorMessage;
			break;
		case "LUWS1001":
			msg = "Order contains invalid commands.";
			break;
		case "LUWS1002":
			msg ="Invalid number of commands in an order (e.g. too many commands in order).";
			break;
		case "LUWS1003":
			msg = "Invalid syntax for field " + errorMessage;
			break;
		case "LUWS1004":
			msg ="Order or command unavailable.";
			break;
		case "LSPG1000":
			msg ="The target command is in an invalid state. Cannot cancel a command that is in the Point Of No Return state.";
			break;
		case "LSPG1056":
			msg = "Invalid VISPID Specified.";
			break;
		case "LSPG1057":
			msg = "BandwidthProduct DSL24MAX is not yet supported.";
			break;
		case "LSPG1058":
			msg ="Cannot Modify a CLI whilst it is currently suspended.";
			break;
	}
	return msg;
}

function neworder(){
	if(!$('li.addeddate').html() && !$('ul#errors').html()) $('#orderbody').hide();
	$('button[name="check"]').live('click', function(){
		$('li.linestatus').slideUp('slow', function(){
			$(this).remove();
		});
		re = /^[\d ]{8,15}$/;
		if(re.test($('input[name="dslnumber"]').val())){
			$(this).after('<img class="loading" src="/images/loading.gif" alt="Loading..." />');
			$.ajax({
				url: "http://www.broadbandfirst.co.uk/ajax.php?do=getlinestatus&num=" + $('input[name="dslnumber"]').val(),
				cache: false,
				success: function(code){
					switch(code){
						case '0':
							var msg = 'ADSL2+ is available for this line.';
							var ok = true;
						break;
						
						case '1':
							var msg = 'ADSL2+ is available for this line. This is a migration and will require a MAC code.';
							var ok = true;
							var migration = true;
						break;
						
						case '2':
							var msg = 'The line number supplied contains an incorrect number of digits.';
						break;
						
						case '3':
							var msg = 'Service cannot be provided due to BT system failure.';
						break;
						
						case '4':
							var msg = 'There are currently no free LLU resources at the requested exchange.';
						break;
						
						case '5':
							var msg = 'Service cannot be provided since the customer to exchange line length is too great.';
						break;
						
						case '6':
							var msg = 'Service not available due to BT problem, please contact our Support department if you require further information.';
						break;
						
						case '7':
							var msg = 'The exchange has not been activated, please contact Support for more information.';
						break;
						
						case '8':
							var msg = 'Our wholesale partners already supply ADSL2+ on this line, please contact support if you wish to place an order.';
						break;
						
						case '9':
							var msg = 'Exchange corresponding to this DSL is now deactive.';
						break;
						
						case '10':
							var msg = 'ADSL2+ is not available on this line. Please contact us for further information.';
						break;
						
						case '11':
							var msg = 'An incompatible product exists on this line. Please contact your line provider for clarification.';
						break;
						
						default:
							var msg = 'There is a problem with this order. Please contact support for further information - 0844 4120820';
						break;
					}
					$('img.loading').remove();
					$('button[name="check"]').closest('li').after('<li class="linestatus"><label>Line Status</label><p>' + msg + '</p></li>');
					if(ok == true){
						$('input[name="issubmit"]').val("1");
						$('li.linestatus').hide().slideDown(function(){
							$('select[name="ordertype"]').find('option').removeAttr('selected');
							if(migration == true) var ordertype = 'Migration';
							else {
								var ordertype = 'New Order';
								$('input[name="migrationcode"]').closest('li').hide();
							}
							$('select[name="ordertype"]').find('option[value="' + ordertype + '"]').attr('selected', 'selected');
							$('input[name="ordertype"]').val(ordertype);
							$('#orderbody').slideDown();
						});
						oddlistsandtables();
						$('button[name="check"]').remove();
					}
				}
			});
		}
		return false;
	});
}

function updatecommitment(){
	$('a#updatecommitment').live('click', function(){
		$(this).hide().next().show();
		return false;
	});
}

function confirmSetup(){
	$('a.setup').live('click', function(){
		return confirm('Are you sure you want to sign up for this service?');
	});
}

function confirmDelete(){
	$('input.delete').livequery('click', function(){
		 return confirm('Are you sure you want to delete this customer?');
	});
}

function autoSubmit(){
	$('form#editPartner select').livequery('change', function(){
		if($(this).val() != 'blank') $('form#editPartner').submit();
	});
}

function oddlistsandtables(){
	$(document).ready(function(){
		$('li, tr').removeClass('odd');
		$('li:odd, tr:odd').addClass('odd');
	});
}

function addDomain(){
	$('input[name="addDomain"]').livequery('click', function(){
		$('#domainForm ul li:last').attr('class', 'buttons ' + $('#domainForm ul li:last').prev().attr('class'));
		if($('#domainForm ul li:last').prev().hasClass('odd')) var liclass = 'even';
		else var liclass="odd";
		$('#domainForm ul li:last').before('<li class="' + liclass + '"><label>www.</label><span class="input"><input type="text" name="domain_name[]" value="" /> <select name="dom_type[]"><option value="co.uk">.co.uk</option><option value="com">.com</option><option value="net">.net</option><option value="org">.org</option><option value="info">.info</option><option value="org.uk">.org.uk</option><option value="me.uk">.me.uk</option><option value="ltd.uk">.ltd.uk</option><option value="name">.name</option><option value="biz">.biz</option><option value="uk.com">.uk.com</option><option value="uk.net">.uk.net</option><option value="gb.com">.gb.com</option></select></span></li>');
		return false;
	});
}

function menuHover(){
	$('#mainmenu > li').hover(
		function(){
			if((($('body').attr('id') == 'index') || ($('body').attr('id') == 'contactus')) && ($(this).attr('class') != 'index') && ($(this).attr('class') != 'contactus')){
				$('#mainmenu > li > a').css('padding', '12px 20px 32px 20px');
				$('#mainmenu').css('padding', '12px 0 32px 0');
			}
		},
		function(){
			if((($('body').attr('id') == 'index') || ($('body').attr('id') == 'contactus')) && ($(this).attr('class') != 'index') && ($(this).attr('class') != 'contactus')){
				$('#mainmenu > li > a').css('padding', '22px 20px');
				$('#mainmenu').css('padding', '22px 0');
			}
		}
	);
}

function portalPicker(){
	$("ul.portalmenu li a").livequery('click', function(){
		if($(this).attr('href') == '#'){
			var link = this;
			var loading = '<div id="loading"><h1>Loading Page</h1><p>Please wait while the page loads</p><p><img src="/images/loading.gif" alt="Loading..." /></p></div>';
			if($(link).attr('class') != 'plesk'){
				$("#page").css('background', 'none').empty();
				$("#noservice").remove();
				$("#iframe").remove();
			}
			switch($(link).attr('class')){
				case 'fail':
					$("#page").append('<div id="noservice"><h1>No Service</h1><p>You don\'t currently have this service with us.  If you would like to add it to your portfolio, please <a href="/contactus/">contact your account manager</a>.</p></div>');
				break;
				case 'index':
					window.location = '/';
				break;
				case 'wlr':
					$("#page").append('<iframe id="iframe" name="iframe" src="http://www.crcsupport.co.uk/wlr/" width="100%" height="700" />');
				break;
				case 'support':
					$("#page").append('<iframe id="iframe" name="iframe" src="http://www.crcsupport.co.uk/" width="100%" height="700" />');
				break;
				case 'plesk':
					$('form#' + $(link).attr("class") + ' input.submit').click();
				break;
				default:
					var src = '';
					switch($(link).attr('class')){					
						case 'ccp1': 	src = 'src="https://www.broadbandmp.co.uk/logout.php"'; 			break;
						case 'ccp2': 	src = 'src="https://corporatebroadband.co.uk/scripts/logout.php"'; 	break;
						case 'adsl2': 	src = 'src="http://adsl2.broadbandfirst.com/logout.php"'; 			break;
						case 'rt': 		src = 'src="http://rt.hostfirst.co.uk/NoAuth/Logout.html"'; 		break;
					}
					$('#page').append('<iframe id="iframe" name="iframe" ' + src + ' />' + loading);
					$('#iframe').hide();
					$('#page').animate(
						{opacity: 1.0}, 
						2000, 
						function(){
							$('#loading').remove();
							$('#iframe').show();
							$('form#' + $(link).attr("class") + ' input.submit').click();
						}
					);
				break;
			}
			$("body").attr('id', $(link).attr('class'));
			return false;
		}
	});
}

function pricingDescriptions(){
	$("table tr.servicedescription").css("display", "none");
	$("table tr.service td.first").prepend('<a href="#">More Info <img src="/images/arrow_down.png" alt="+" /></a> - ');
	$("table tr.service td.first a").toggle(
		function(){
			$("table tr.service td.first a img").replaceWith('<img src="/images/arrow_down.png" alt="+" />');
			$("table tr.servicedescription").hide();
			$(this).parent().parent().next().show();
			$(this).find('img').replaceWith('<img src="/images/arrow_up.png" alt="-" />');
			return false;
		},
		function(){
			$("table tr.service td.first a img").replaceWith('<img src="/images/arrow_down.png" alt="+" />');
			$("table tr.servicedescription").hide();
			$(this).find('img').replaceWith('<img src="/images/arrow_down.png" alt="+" />');
			return false;
		}
	);
}

function selectMenu(){
	$("#choose li.index a").livequery('click', function(someval){
		if($("#choose ul").css('display') == 'block') $("#choose ul").slideUp('fast');
		else $("#choose ul").slideDown('fast');
		
		if($("#choose ul").css('display') == 'block') $("#choose li.index").mouseleave(function(){
			setTimeout(function(){
				$("#choose ul").slideUp('fast')
			}, '200');
		});
	});
}

function previewImage(){
	$('ul.sampledetails li a').livequery('click', function(){
		openModalWindow();
		$('#modalcontent').append('<img src="' + $(this).attr('href') + '" />');
		$('#modalcontent img').load(function(){
			resizeModalWindow();
		});
		return false;
	});
}

function openModalWindow(content){
	if($('#mask').length == 0){
		$('body').prepend('<div id="mask"><div id="modalbox">' + content + '</div></div>');
		$('#mask').hide();
		$('#mask').fadeIn(600);
		//Get the screen height and width  
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
		
		//Set height and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		resizeModalWindow();
	}
}

function resizeModalWindow(){
	//Get the modal box height and width
	var winH = $(window).height();
	var winW = $(window).width();
	
	//Set the popup window to center
	$('#modalbox').css('top',  ((winH/2)-($('#modalbox').height()/2)));
	$('#modalbox').css('left', ((winW/2)-($('#modalbox').width()/2)));
}

function closeModalWindow(){
	$('#mask').fadeOut(500, function(){
		$('#mask').remove();
	});
}

function triggerCloseModalWindow(){
	$('#modalbox a.close').livequery('click', function(){
		closeModalWindow();
		return false;
	});
	
	$('*').keypress(function(e){
		if(e.keyCode == 27) closeModalWindow();
	});
}

function strPad(i,l,s) {
	var o = i.toString();
	if (!s) { s = '0'; }
	while (o.length < l) {
		o = s + o;
	}
	return o;
};