﻿var ControlID = 'ctl00_MasterContentPlaceHolder_';

// JScript File

function ShowNewWindow(sURL)
{
    var lTop = (screen.availHeight-450)/2;
    var lWidth = (screen.availWidth-600)/2;
    var objRetVal = window.open(sURL,'TC',
                      'directories=no,height=450,width=600,top='+lTop+',left='+lWidth+',chrome,centerscreen,dependent=yes, dialog=yes,modal=YES,resizable=YES,scrollbars=YES, location=0,status=0,menubar=0,toolbar=0');
    objRetVal.focus();
    if (objRetVal == null)
        alert('Your popup blocker wont`t allow you access to this feature');
   return false;
}

//Used for the flash graph drawing
function setFCNewData(objFlash, strXML) {
     //This function updates the data of a FusionCharts present on the page
     //Get a reference to the movie      
     var FCObject = getObject(objFlash);
     //Set the data
     //Set dataURL to null
     FCObject.SetVariable('_root.dataURL',"");
     //Set the flag
     FCObject.SetVariable('_root.isNewData',"1");
     //Set the actual data
     FCObject.SetVariable('_root.newData',strXML);
     //Go to the required frame
     FCObject.TGotoLabel('/', 'JavaScriptHandler');     
}

function getObject(objectName) {
     if (navigator.appName.indexOf ("Microsoft") !=-1) {
          return window[objectName]
     } else {
          return document[objectName]
     }
}

// Added for quoting wizard - needs tidying up
// JScript File


 

function Move4Us_Referral_AddressChanged(objAddress, PostCodeControlID)
{      
	objAdd=objAddress;
    document.getElementById(ControlID + 'AddressRef').value=objAddress.Ref;
	document.getElementById(ControlID + 'AddressSubBuildingName').value=objAddress.SubBuildingName;
	document.getElementById(ControlID + 'AddressLine1').value=objAddress.Line1;
	document.getElementById(ControlID + 'AddressLine2').value=objAddress.Line2;
	document.getElementById(ControlID + 'AddressTown').value=objAddress.Town;
	document.getElementById(ControlID + 'AddressCounty').value=objAddress.County;
	document.getElementById(ControlID + 'AddressPostcode').value=objAddress.Postcode;
	document.getElementById(ControlID + 'AddressCountryId').value=objAddress.CountryId;     
        
    //Set LR lookup status before doing the lookup
    document.getElementById(ControlID + 'LandRegistryLookupOK').value='-1';

    Move4Us_Referral_UpdateAddressSummary();
    Move4Us_Referral_AddressCheck();
}

function Move4Us_Referral_AddressCheck()
{
    if (document.getElementById(ControlID + 'AddressRef').value!='Manual')
    {
        var sURL='HIPReferralService.asmx?method=AddressCheck&AddressRef=' + objAdd.Ref + '&DecacheId=' + Math.random() ;;
        AddressCheck = window.XMLHttpRequest ? new XMLHttpRequest()
                    : new ActiveXObject('Microsoft.XMLHTTP');
        AddressCheck.onreadystatechange = Move4Us_Referral_AddressCheck_Callback;
        AddressCheck.open('GET',encodeURI(sURL),true);
        AddressCheck.send('');
    }
    else
    {
        //unable to do lookup due to manually entered address - set to Registered/freehold
        document.getElementById(ControlID + 'LocalAuthoritySelector').value = '-1';
        document.getElementById(ControlID + 'LocalAuthoritySelector').disabled = '';
        document.getElementById(ControlID + 'LandRegistryLookupOK').value='0';
        document.getElementById(ControlID + 'LocalAuthorityTextbox').value = "";
        //Set value of hidden field
        Move4Us_Dropdown2Textbox("", 'txtLocalAuthoritySelector');
    }
}

function Move4Us_Referral_AddressCheck_Callback()
{
    if (AddressCheck.readyState == 4) // Request completed
    {
        if (AddressCheck.status == 200) // Request finished OK
        {
            if (AddressCheck.responseText != 'ERROR')
            {
                var Response = new Array();
                Response = AddressCheck.responseText.split(',');              
                document.getElementById(ControlID + 'LocalAuthoritySelector').value = Response[0];
                document.getElementById(ControlID + 'LocalAuthorityTextbox').value = document.getElementById(ControlID + 'LocalAuthoritySelector').options[document.getElementById(ControlID + 'LocalAuthoritySelector').selectedIndex].text;
                //Set value of hidden field
                Move4Us_Dropdown2Textbox(Response[0], 'txtLocalAuthoritySelector');
            }
        }
        else
        {
            //unable to do lookup set to Registered/please specify
            document.getElementById(ControlID + 'LocalAuthoritySelector').value = '-1';
	        document.getElementById(ControlID + 'LandRegistryLookupOK').value='0';
            document.getElementById(ControlID + 'LocalAuthorityTextbox').value = "";
            //Set value of hidden field
            Move4Us_Dropdown2Textbox("", 'txtLocalAuthoritySelector');
        }
    }
} 


function Move4Us_Referral_UpdateAddressSummary()
{
	var sSummary='';
	var sFullAddress='';
	var sAddressLine1;
	var sAddressLine2;
	var sAddressTown;
	var sAddressCounty;
	var sAddressPostcode;
	var sAddressRef;

	sAddressLine1=document.getElementById(ControlID + 'AddressLine1').value;
	sAddressLine2=document.getElementById(ControlID + 'AddressLine2').value;
	sAddressTown=document.getElementById(ControlID + 'AddressTown').value;
	sAddressCounty=document.getElementById(ControlID + 'AddressCounty').value;
	sAddressPostcode=document.getElementById(ControlID + 'PostcodeSearch_Postcode').value;
	sAddressRef=document.getElementById(ControlID + 'AddressRef').value;

	if(sAddressLine1.length>0)
	{
		sFullAddress+=sAddressLine1;
	}
	
	if(sAddressLine2.length>0)
	{
		if(sFullAddress.length>0){sFullAddress+=', '}
			sFullAddress+=sAddressLine2;
	}
	if(sAddressTown.length>0)
	{
		if(sFullAddress.length>0){sFullAddress+=', '}
			sFullAddress+=sAddressTown;
	}
	if(sAddressCounty.length>0)
	{
		if(sFullAddress.length>0){sFullAddress+=', '}
			sFullAddress+=sAddressCounty;
	}
	if(sAddressPostcode.length>0)
	{
		if(sFullAddress.length>0){sFullAddress+=', '}
			sFullAddress+=sAddressPostcode;
	}
	document.getElementById(ControlID + 'AddressLookup').value=sFullAddress;
}   

function Move4Us_ValidateCommission(commission)
{
    var returnval;
       
    if (commission.length==0)
    {
        returnval = '2.00';
    }    
    else
    {  
        if (commission.indexOf(".") < 0)
        {
            //No decimal point so just return the number
            returnval = commission.replace(/[^0-9]+/g,'') + '.00';
        }
        else
        {
            //String has decimal point
            var beforepoint = commission.substring(0,commission.indexOf(".")).replace(/[^0-9]+/g,'');
            var afterpoint = commission.substring(commission.indexOf("."),commission.length).replace(/[^0-9]+/g,'');
            returnval = beforepoint + '.' + afterpoint;
            if (commission.indexOf(".") == 0)
            {
                //decimal point appears first so pad with zero
                returnval = '0' + returnval;
            }
            else if (commission.indexOf(".") == commission.length-1)
            {
                //decimal point appears last so pad with zeros
                returnval = returnval + '00';
            }
        }
    }
    return returnval = returnval + "%";
}

function Move4Us_ValidateNumeric(FieldName, MinValue, MaxValue, ShowValidationError)
{
       //remove any none numeric chars
        var sFieldValue = document.getElementById(ControlID + FieldName).value.replace(/[^0-9]+/g,'');
    
        if(isNaN(sFieldValue) || (sFieldValue.length==0) || (sFieldValue < MinValue) || (sFieldValue > MaxValue)) 
        {
            //If the field is not a number or is nothing - show validation warning
            document.getElementById(ControlID + FieldName).value = document.getElementById(ControlID + FieldName).value.replace(/[^0-9]+/g,'');
            if (ShowValidationError == 'ShowValidationError')
            {
                Move4Us_ToggleErrorContainer(ControlID + FieldName, 'show');
            }
        }
        else 
        {
            if (ShowValidationError == 'ShowValidationError')
            {
                Move4Us_ToggleErrorContainer(ControlID + FieldName, 'hide');
                document.getElementById(ControlID + FieldName).value = sFieldValue;
            } 
        }
}

function Move4Us_ValidateCurrency(FieldName, ShowValidationError)
{
        //remove any currency symbols and commas
        var sFieldValue = document.getElementById(ControlID + FieldName).value.replace(/[^0-9]+/g,'');
    
        if(isNaN(sFieldValue) || (sFieldValue.length==0) || (sFieldValue < 50000)) 
        {
            //If the field is not a number or is nothing - show validation warning
            document.getElementById(ControlID + FieldName).value = "£" + document.getElementById(ControlID + FieldName).value.replace(/[^0-9]+/g,'');
            if (ShowValidationError == 'ShowValidationError')
            {
                Move4Us_ToggleErrorContainer(ControlID + FieldName, 'show');
            }
        }
        else 
        {
            document.getElementById(ControlID + FieldName).value = "£" + Move4Us_addCommas(sFieldValue);
            if (ShowValidationError == 'ShowValidationError')
            {
                Move4Us_ToggleErrorContainer(ControlID + FieldName, 'hide');
            } 
        }
    
}

function Move4Us_addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
	    x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function Move4Us_ValidateStep1()
{
    bFormValid=true;
    
    //Contact Details
    Move4Us_ValidateFieldString(ControlID + 'ClientTitle', null, 'Name');
    Move4Us_ValidateFieldString(ControlID + 'Forename', null, 'Name');
    Move4Us_ValidateFieldString(ControlID + 'Surname', null, 'Name');
    Move4Us_ValidateEmailAddress(ControlID + 'EmailAddress');
    
    //First parameter is always the validation error field to show if numbers dont pass validation tests.
    Move4Us_ValidateTelephoneNumbers([ControlID + 'MainTelephone', ControlID + 'AltTelephone'],[ControlID + 'MainTelephone', ControlID + 'AltTelephone']); 

    //Property being sold details
    Move4Us_ValidateFieldString(ControlID + 'AddressLookup', '(Please search for your address using the address lookup wizard above)');
    Move4Us_ValidateNumeric('NumberOfBedrooms', 1, 99, 'ShowValidationError');
    Move4Us_ValidateCurrency('SalePrice', 'ShowValidationError');
    return bFormValid;
}


function Move4Us_ValidateStep2()
{
    if (document.getElementById(ControlID + 'SelectedMarketingPackage').value.toString().trim().length == 0)
    {
        document.getElementById('PackageSelectionErrorMessage').style.display='';
        return false;
    }
    else
    {
        document.getElementById('PackageSelectionErrorMessage').style.display='none';    
        return true;
    }
}

function Move4Us_ToggleExtras(Field, State)
{
    document.getElementById(ControlID + Field).style.display = State;
}


//Form Field Validation Functions
    function Move4Us_ValidateFieldString(FieldName, BadStringMatch, OverrideFieldName) 
    {
        if ((document.getElementById(FieldName).value.toString().trim().length == 0) || (document.getElementById(FieldName).value.toString() == BadStringMatch))
        {
            if (OverrideFieldName != null)
            {
                FieldName = ControlID + OverrideFieldName;
            }
            //String is empty  - show validation warning
            Move4Us_ToggleErrorContainer(FieldName, 'show'); 
        }
        else
        {
            if (OverrideFieldName != null)
            {
                FieldName = ControlID + OverrideFieldName;
            }
            Move4Us_ToggleErrorContainer(FieldName, 'hide');
        }
    }

    function Move4Us_ValidateFieldNumeric(FieldName) 
    {
        //remove any currency symbols and commas
        var sFieldValue = document.getElementById(FieldName).value.replace(/[£,]/g,"");
  
        if(isNaN(sFieldValue) || (sFieldValue.length==0)) 
        {
            //If the field is not a number or is nothing - show validation warning
            Move4Us_ToggleErrorContainer(FieldName, 'show');           
        }
        else 
        {
            Move4Us_ToggleErrorContainer(FieldName, 'hide'); 
        }
    }


    function Move4Us_ValidateSelector(FieldName)
    {
        if (document.getElementById(FieldName).value=='-1') 
        {
            //Not a valid selection - show validation warning
            Move4Us_ToggleErrorContainer(FieldName, 'show');     
        }
        else
        {
            Move4Us_ToggleErrorContainer(FieldName, 'hide'); 
        }
    }

    function Move4Us_ValidateEmailAddress(FieldName)
    {
        if (document.getElementById(FieldName).value.checkEmail()==false)            
        {
            //Not a valid email address - show validation warning
            document.getElementById(FieldName + '_ErrorMessageContainer').innerHTML='Please enter a valid email address';
            Move4Us_ToggleErrorContainer(FieldName, 'show'); 
        }     
        else 
        {
            document.getElementById(FieldName + '_ErrorMessageContainer').innerHTML='Please enter your email address';
            Move4Us_ToggleErrorContainer(FieldName, 'hide'); 
        }
    }

    function Move4Us_ValidateTelephoneNumbers(ValidationErrorFieldNames,FieldNames)
    { 
        var strPatters = /.\d+.*\d+.*\d+.*\d+.*\d+.*\d+.*\d+.*/;
        var regex = new RegExp(strPatters);
        var bOneValidNumberFound = false;
        
        for(i=0; i<FieldNames.length; i++)
        {
            if (regex.test(document.getElementById(FieldNames[i]).value.toString().trim()) == true)
            {
                bOneValidNumberFound = true;
                break;
            }
        }

        if (bOneValidNumberFound == false)
        {
            for(i=0; i<ValidationErrorFieldNames.length; i++)
            {
                Move4Us_ToggleErrorContainer(ValidationErrorFieldNames[i], 'show');
            }
        }
        else 
        {
            for(i=0; i<ValidationErrorFieldNames.length; i++)
            {
                Move4Us_ToggleErrorContainer(ValidationErrorFieldNames[i], 'hide');
            }            
        }
    }
    
    function Move4Us_ToggleErrorContainer(FieldName, State)
    {
        if  (State=='show')
        {
            //Each field has a container which contains the label, field and error message container
            //When validation fails we set the container class to FieldValidationerror (highlighted background color)
            //and we show the errormessagecontainerdiv which helps the user complete the field correctly
            document.getElementById(FieldName + '_ErrorMessageContainer').style.display='block';
            document.getElementById(FieldName + '_Container').className='FieldValidationerror';
            bFormValid = false;
        }
        else 
        {
            //When the field validation is successful we hide the error message and return the container back to normal colour
            document.getElementById(FieldName + '_ErrorMessageContainer').style.display='none';
            document.getElementById(FieldName + '_Container').className='Field'; 
        }
    }
//END Form Field Validation Functions

function Move4Us_IntegerFieldCleanString(sender)
{
    var value = sender.value;   
    var rx = new RegExp(/[^0-9]/g);
    value = value.replace(rx, "");
    sender.value = value;
}

function Move4Us_DecimalFieldCleanString(sender)
{
    var value = sender.value;   
    var rx = new RegExp(/[^0-9.]/g);
    value = value.replace(rx, "");
    sender.value = value;
}

function Move4Us_TelephoneFieldCleanString(sender)
{
    var value = sender.value;   
    var rx = new RegExp(/[^0-9 +.]/g);
    value = value.replace(rx, "");
    sender.value = value;
}

function Move4Us_StripUnsafeChars(fieldId) {
	var field = $(fieldId);
	if (field && field.value && field.value.length > 0) {
		var replaceRgx = new RegExp("[\\/<>]", "g");
		field.value = field.value.replace(replaceRgx, "");
	}
}

String.prototype.checkEmail = function()
{
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(this))
        {
        return (true);
        }
    return (false);
}

String.prototype.trim = function()
{
    var sRetVal;
    
    sRetVal = this.replace(/^[\s]+/g,'');
    sRetVal = this.replace(/[\s]+$/g,'');

    return sRetVal; 
}

function Move4Us_Dropdown2Textbox(FieldValue, TargetFieldName)
{
    document.getElementById(ControlID + TargetFieldName).value = FieldValue;
}
