﻿
var curLocPos = -1;
Event.observe(window, 'load', function() {
var oTextbox = new AutoSuggestControl(document.getElementById("l_c"));
$("location_town").observe("click", locChange);
$("location_postcode").observe("click", locChange);
});

function AutoSuggestControl(oTextbox) {
    
    this.textbox  = oTextbox;
    
    //initialize the control
    this.init();
    
}
 
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;
    
    showHideComboBody("hide");
    
    //assign the onkeyup event handler
    this.textbox.onkeyup = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyUp() method with the event object
        oThis.handleKeyUp(oEvent);
    };
    
    this.textbox.onkeydown = function (oEvent) {
    
        //check for the proper location of the event object
        if (!oEvent) {
            oEvent = window.event;
        }    
        
        //call the handleKeyDown() method with the event object
        oThis.handleKeyDown(oEvent);
    };
};

AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {

    switch(oEvent.keyCode) {
        case 38: //up arrow
            clearLocSel();
            curLocPos--;
            if(document.getElementById("locSel_"+curLocPos))
            {
                
                document.getElementById("locSel_"+curLocPos).style.backgroundColor='#e6f0fe'
                document.getElementById("l_c").value=document.getElementById("locVal"+curLocPos).value;
            }
            else
            {
                curLocPos=10;
                while(!document.getElementById("locSel_"+curLocPos)&&cuLocPos!=-1)
                {
                    curLocPos--;
                }
                if(document.getElementById("locSel_"+curLocPos))
                {
                    document.getElementById("locSel_"+curLocPos).style.backgroundColor='#e6f0fe'
                    document.getElementById("l_c").value=document.getElementById("locVal"+curLocPos).value;
                }
            }
            break;
        case 40: //down arrow 
            clearLocSel();
            curLocPos++;
            if(document.getElementById("locSel_"+curLocPos))
            {
                
                document.getElementById("locSel_"+curLocPos).style.backgroundColor='#e6f0fe'
                document.getElementById("l_c").value=document.getElementById("locVal"+curLocPos).value;
            }
            else
            {
                curLocPos=0;
                if(document.getElementById("locSel_"+curLocPos))
                {
                    document.getElementById("locSel_"+curLocPos).style.backgroundColor='#e6f0fe'
                    document.getElementById("l_c").value=document.getElementById("locVal"+curLocPos).value;
                }
            }
            break;
        case 9: //tab
        case 13: //enter
            if(curLocPos!=-1)
            {
                
            }
            break;
        case 27: //escape
            showHideComboBody("hide");
            break;
    }

};

AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {
    var iKeyCode = oEvent.keyCode;

    if (iKeyCode == 13 || iKeyCode == 9)
    {
        showHideComboBody("hide");
    }
    //for backspace (8) and delete (46), shows suggestions without typeahead
    if (iKeyCode == 8 || iKeyCode == 46) {
        autoCheck();
        
    //make sure not to interfere with non-character keys
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) {

    } else {
       autoCheck();
    }
};
function disableEnterKey(e)
{
    var key;
     
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}




function autoCheck()
{
	var comboBodyObject = document.getElementById("locDrop");
	var comboHeader = document.getElementById("l_c");
	comboBodyObject.style.left=findPos(comboHeader)[0]+'px'; 
	comboBodyObject.style.top=(findPos(comboHeader)[1]+18)+'px'; 
    document.getElementById("locDrop").innerHTML = "<div style=\"width:250px; background-color:#ffffff; border:solid 1px #999999;\">loading...</div>";
    new Ajax.Request('/jobs/ajax/locationsAutocomplete.aspx', {parameters:'town='+document.getElementById("l_c").value, onSuccess:locFunc, onFailure:locError });
}
	
var locFunc = function(t) {
    document.getElementById("locDrop").innerHTML = t.responseText
    if(t.responseText!="")
        showHideComboBody("show");
}

var locError = function(t)
{
    alert('Error ' + t.status + ' -- ' + t.statusText);
}

function clearLocSel()
{
    cnt=0;
    while (cnt<10)
    {
        if(document.getElementById("locSel_"+cnt))
        {
             document.getElementById("locSel_"+cnt).style.backgroundColor='#ffffff';
        }
        else
            break;
            
       cnt++;
    }
}

function showHideComboBody(action)
{
	var comboBodyObject = document.getElementById("locDrop");
	var comboHeader = document.getElementById("l_c");
	comboBodyObject.style.left=(findPos(comboHeader)[0]-5)+'px'; 
	comboBodyObject.style.top=(findPos(comboHeader)[1]+22)+'px'; 
	
	if (action=="show")
	{
		comboBodyObject.style.display='block';
		comboBodyObject.style.overflow = "auto";
	}
	else
	{
		comboBodyObject.style.display='none';
		comboBodyObject.style.overflow = "hidden";	
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}


window.onresize = function(e) {
    var comboBodyObject = document.getElementById("locDrop");
	var comboHeader = document.getElementById("l_c");
	comboBodyObject.style.left=findPos(comboHeader)[0]+'px'; 
	comboBodyObject.style.top=(findPos(comboHeader)[1]+18)+'px';

}

document.onclick  = function() {
	setTimeout('delayedClickTest()', 50);
}

function delayedClickTest(oldComboObj)
{
    cuLocPos=-1;
	showHideComboBody("hide");
}


function locChange(e)
{
    var el = e.target;
    var hideEl, showEl;
    var newHeight = 23;
    if (Element.hasClassName(el, "selected") == false)
    {
        if (el.id == "location_town")
        {
            postTown = true;
            Element.addClassName("location_town", "selected");
            Element.removeClassName("location_postcode", "selected");
            showEl = document.getElementById("postcodeTownDiv");
            hideEl = document.getElementById("postcodeDiv");
            newHeight = 21;
            document.getElementById("location_tabs").style.backgroundImage = "url(/images/construction/jobs/search_panel_loc_tabs_town.gif)"; 
        }
        else
        {
            postTown = false;
            Element.addClassName("location_postcode", "selected");
            Element.removeClassName("location_town", "selected");
            showEl = document.getElementById("postcodeDiv");
            hideEl = document.getElementById("postcodeTownDiv");
            newHeight = 23;
            document.getElementById("location_tabs").style.backgroundImage = "url(/images/construction/jobs/search_panel_loc_tabs_postcode.gif)";
        }
        
        showEl.style.display = "block";
        showEl.style.height = "0px";
        hideEl.style.display = "block";
        hideEl.style.height = newHeight + "px";
        
        document.getElementById('p_c').value="Postcode";
        document.getElementById('radius').selectedIndex=9;
        document.getElementById('l_c').value="City/Town";
        hideEl.style.display = "none";
       /* var t = new Tween(hideEl.style, 'height', Tween.strongEaseInOut, 0, 0, .1, 'px');
        t.addListener({
                onMotionFinished : function() {
                    hideEl.style.display = "none";
                }
        });
        t.fixTime;
        t.start();*/
        
        t = new Tween(showEl.style, 'height', Tween.strongEaseInOut, parseInt(showEl.style.height), newHeight, .4, 'px');
        t.fixTime;
        t.start();
    }
    e.preventDefault();
    //return false;
}


function validatePostcode()
{
    
     document.getElementById("aspnetForm").action = "/jobs/results/";
     document.getElementById("aspnetForm").method = "get";
    if(document.getElementById("p_c").value!="Postcode")
    {
        result = postcodeCheck(document.getElementById("p_c").value);

        if (result == "") 
        {
            new Ajax.Request('/jobs/ajax/validatePostcode.aspx', { parameters: 'postcode=' + document.getElementById("p_c").value, onSuccess: postcodeFunc, onFailure: postcodeError });
        }
        else
            alert(result);
            
        return false;
    }
    else
        return true;


    
    
}
	
var postcodeFunc = function(t) {
    
    if(t.responseText=="ok")
        document.getElementById("aspnetForm").submit();
    else
        alert('This does not appear to be a valid postcode');
}

var postcodeError = function(t)
{
    alert('Problem validating postcode');
}


function postcodeCheck(test){ //check postcode format is valid
 size = test.length
 test = test.toUpperCase(); //Change to uppercase
 while (test.slice(0,1) == " ") //Strip leading spaces
  {test = test.substr(1,size-1);size = test.length
  }
 while(test.slice(size-1,size)== " ") //Strip trailing spaces
  {test = test.substr(0,size-1);size = test.length
  }
  
 if (size < 6 || size > 8){ //Code length rule
  return "'"+test + "' is not a valid postcode - wrong length";
  }
 if (!(isNaN(test.charAt(0)))){ //leftmost character must be alpha character rule
   return ("'"+test + "' is not a valid postcode - cannot start with a number");
  }
 if (isNaN(test.charAt(size-3))){ //first character of inward code must be numeric rule
   return ("'"+test + "' is not a valid postcode - alpha character in wrong position");
  }
 if (!(isNaN(test.charAt(size-2)))){ //second character of inward code must be alpha rule
   return ("'"+test + "' is not a valid postcode - number in wrong position");
  }
 if (!(isNaN(test.charAt(size-1)))){ //third character of inward code must be alpha rule
   return ("'"+test + "' is not a valid postcode - number in wrong position");
  }
 if (!(test.charAt(size-4) == " ")){//space in position length-3 rule
   return ("'"+test + "' is not a valid postcode - no space or space in wrong position");
   }
 count1 = test.indexOf(" ");count2 = test.lastIndexOf(" ");
 if (count1 != count2){//only one space rule
   return ("'"+test + "' is not a valid postcode - only one space allowed");
  }
  
return "";
}