function JSCalcExpression(this_id, formula)
{
  if (document.getElementById(this_id)) document.getElementById(this_id).value = formula;
}

function getStacked()
{
	var max_buildings = 8;
  var stacked_array = new Array();
  with(document.getElementById('form_search_building'))
  {
	for (c = 0; c < elements.length; c++) {
		if (elements[c].name == 'f[]') {
			if (elements[c].checked == 1)
			{
			  stacked_array.push(elements[c].value)
			}
		}
	}

	//if (stacked_array.length > 0 && stacked_array.length <= 6)
	if (stacked_array.length > 0 && stacked_array.length <= 8)
	{
	  redirect_string = "/index_en.php?page=stacked_availability";
	  for (i = 0; i < stacked_array.length; i++)
	  {
		redirect_string = redirect_string + "&bldgid[]=" + stacked_array[i];
	  }
	  window.location = redirect_string;
	}
	else {
		alert('Please select one to eight buildings');
	}
  }
}

function validate_required_broker(field_id1, val_def1, n1, field_id2, val_def2, n2)
{
  input_obj1 = document.getElementById(field_id1);
  input_obj2 = document.getElementById(field_id2);

  var ret = true;
  var alert_text = '';
  var focused = false;

  if (input_obj1.value==null || input_obj1.value=="" || input_obj1.value==val_def1)
  {
	alert_text += n1 + ' must not be empty.\n';
	input_obj1.focus();
	focused = true;
	ret = false;
  }

 // if (input_obj2.value==null || input_obj2.value=="" || input_obj2.value==val_def2)
 // {
//	alert_text += n2 + ' must not be empty.\n';
//	if (!focused) input_obj2.focus();
//	focused = true;
//	ret = false;
 // }

  if (!ret) alert(alert_text);

  return   ret;
}

function validate_required(field_id1, val_def1, n1, field_id2, val_def2, n2, field_id3, val_def3, n3)
{
  input_obj1 = document.getElementById(field_id1);
  input_obj2 = document.getElementById(field_id2);
  input_obj3 = document.getElementById(field_id3);

  var ret = true;
  var alert_text = '';
  var focused = false;

  if (input_obj1.value==null || input_obj1.value=="" || input_obj1.value==val_def1)
  {
	alert_text += n1 + ' must not be empty.\n';
	input_obj1.focus();
	focused = true;
	ret = false;
  }

  if (input_obj2.value==null || input_obj2.value=="" || input_obj2.value==val_def2)
  {
	alert_text += n2 + ' must not be empty.\n';
	if (!focused) input_obj2.focus();
	focused = true;
	ret = false;
  }

  if (input_obj3.value==null || input_obj3.value=="" || input_obj3.value==val_def3)
  {
	alert_text += n3 + ' must not be empty.\n';
	if (!focused) input_obj3.focus();
	ret = false;
  }

  if (parseInt(input_obj2.value) <= 0)
  {
	alert_text += n2 + ' must be greater than zero.\n';
	if (!focused) input_obj2.focus();
	ret = false;
  }

  if (parseInt(input_obj2.value) > parseInt(input_obj3.value))
  {
	alert_text += n2 + ' must be smaller than ' + n3 + '.\n';
	if (!focused) input_obj2.focus();
	ret = false;
  }

  if (!ret) alert(alert_text);

  return   ret;
}

function populateGeozoneDropdown_old(this_id, product_id, target)
{
  textbox = document.getElementById(this_id);
  product_industrial = document.getElementById(product_id + '_industrial');
  product = 'office';
  if (product_industrial.checked == true) product = 'industrial';
  ur = 'index_en.php?page=searchresultajax&searchby=by_geozone&geozone=' + textbox.value + '&product=' + product + '&target=' + target;

//  alert(ur);

  ConnectAjax(ur, 3);
}

function populateGeozoneDropdown(product_id, target)
{
  product_industrial = document.getElementById(product_id + '_industrial');
  product = 'office';
  if (product_industrial.checked == true) product = 'industrial';
  ur = 'index_en.php?page=searchresultajax&searchby=by_geozone&product=' + product + '&target=' + target;

//  alert(ur);

  ConnectAjax(ur, 3);
}

function reloadPerspective(type)
{
  window.location = "index.php?tab=perspective&type=" + type;
}

window.onload = function () {
  // Comment the line off to turen off Autosuggestion

  //var oTextbox1 = new AutoSuggestControl(document.getElementById("location"), new Suggestions());
  //var oTextbox2 = new AutoSuggestControl(document.getElementById("building_name"), new Suggestions());
  //var oTextbox3 = new AutoSuggestControl(document.getElementById("locationb"), new Suggestions());
  //var oTextbox4 = new AutoSuggestControl(document.getElementById("broker_name"), new Suggestions());
  //var oTextbox5 = new AutoSuggestControl(document.getElementById("building_name2"), new Suggestions());
  //var oTextbox7 = new AutoSuggestControl(document.getElementById("UpdateCompany"), new Suggestions());
}


// BD
//--------------------------------------- AJAX tools and Autosuggestion start
var http_request = false; // reset http_request
var http_request_img = false; // reset http_request

/**
 * An autosuggest textbox control.
 * @class
 * @scope public
 */

var suggestControl = null; //
//var timestampEvent = 0; //

//var eventGlobal = null; //

function AutoSuggestControl(oTextbox /*:HTMLInputElement*/, oProvider /*:SuggestionProvider*/) {
    /**
     * The currently selected suggestions.
     * @scope private
     */
    this.cur /*:int*/ = -1;

    /**
     * The dropdown list layer.
     * @scope private
     */
    this.layer = null;

    /**
     * Suggestion provider for the autosuggest feature.
     * @scope private.
     */
    this.provider /*:SuggestionProvider*/ = oProvider;


	this.timestampEvent = 0;
	this.timestampStart = 0;

    /**
     * The textbox to capture.
     * @scope private
     */
    this.textbox /*:HTMLInputElement*/ = oTextbox;

    //initialize the control
    this.init();
}

/**
 * Provides suggestions class.
 * @class
 * @scope public
 */
function Suggestions() {
}

/**
 * Request suggestions for the given autosuggest control.
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
Suggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/, iKeyCode /*:boolean*/) {
    var sTextbox = oAutoSuggestControl.textbox;

    if (sTextbox.value.length <= 0)
	{
	  oAutoSuggestControl.hideSuggestions();
	  return;
	}

//    if (sTextbox.value.length <= 3)
//	{
//	  return;
//	}

    systemid = 1;
    i2 = null;
	i3 = null;

    switch(sTextbox.id)
    {
        case 'location':
                searchby = 'by_loc';
                i1 = 'location';
            break;
        case 'building_name':
				searchby = 'by_name_full';
                i1 = 'building_name';
            break;
        case 'building_name2':
                searchby = 'by_name_full2';
                i1 = 'building_name2';
            break;
        case 'locationb':
                searchby = 'by_loc';
                i1 = 'location';
            break;
        case 'broker_name':
                searchby = 'by_contact';
                i1 = 'contact';
                i2 = 'location';
                v2 = 'locationb';
			break;
        case 'UpdateCompany':
                searchby = 'by_company';
                i1 = 'UpdateCompany';
                i3 = 'UpdateSearchFor';
			break;
    }

    suggestControl = oAutoSuggestControl;

    ur = 'index_en.php?page=searchresultajax&system=' + systemid  + '&searchby=' + searchby + '&' + i1 + '=' + sTextbox.value ;
    //ur = ur + '&type=simple';
    if (i2)
    {
        var tbox = document.getElementById(v2);
        ur = ur + '&' + i2 + '=' + tbox.value;
    }
    if (i3)
    {
        var tbox = document.getElementById(i3);
        ur = ur + '&' + i3 + '=' + tbox.value;
    }


//alert(ur);

    ConnectAjax(ur, 2);
};

// -

/**
 * Autosuggests one or more suggestions for what the user has typed.
 * If no suggestions are passed in, then no autosuggest occurs.
 * @scope private
 * @param aSuggestions An array of suggestion strings.
 * @param bTypeAhead If the control should provide a type ahead suggestion.
 */
AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/, bTypeAhead /*:boolean*/) {
    //make sure there's at least one suggestion
    if (aSuggestions.length > 0) {
        if (bTypeAhead) {
           this.typeAhead(aSuggestions[0]);
        }
      this.showSuggestions(aSuggestions);
    } else {
        this.hideSuggestions();
    }
};

/**
 * Creates the dropdown layer to display multiple suggestions.
 * @scope private
 */
AutoSuggestControl.prototype.createDropDown = function ()
{
    var oThis = this;

    //create the layer and assign styles
    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    //this.layer.style.width = this.textbox.offsetWidth; // Mar 5 (CS) : COMMENTED OUT THIS LINE TO FIX WIDTH ISSUE WITH TABS

    //when the user clicks on the a suggestion, get the text (innerHTML)
    //and place it into a textbox
    this.layer.onmousedown =
    this.layer.onmouseup =
    this.layer.onmouseover = function (oEvent) {
        oEvent = oEvent || window.event;
        oTarget = oEvent.target || oEvent.srcElement;

        if (oEvent.type == "mousedown") {
            oThis.textbox.value = oTarget.firstChild.nodeValue;
            oThis.hideSuggestions();
        } else if (oEvent.type == "mouseover") {
            oThis.highlightSuggestion(oTarget);
        } else {
            oThis.textbox.focus();
        }
    };

    document.body.appendChild(this.layer);
};

/**
 * Gets the left coordinate of the textbox.
 * @scope private
 * @return The left coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getLeft = function () /*:int*/ {
/*
    var oNode = this.textbox;
    var iLeft = 0;

    while(oNode.tagName != "BODY") {
        iLeft += oNode.offsetLeft;
        oNode = oNode.offsetParent;
    }

    return iLeft;
*/
  return $(this.textbox).offset().left;
};

/**
 * Gets the top coordinate of the textbox.
 * @scope private
 * @return The top coordinate of the textbox in pixels.
 */
AutoSuggestControl.prototype.getTop = function () /*:int*/ {
/*
    var oNode = this.textbox;
    var iTop = 0;

    while(oNode.tagName != "BODY") {
        iTop += oNode.offsetTop;
        oNode = oNode.offsetParent;
    }

    return iTop;
*/
  return $(this.textbox).offset().top;
};

/**
 * Gets the width of the textbox.
 * @scope private
 * @return The width of the textbox in pixels.
 */
AutoSuggestControl.prototype.getWidth = function () /*:int*/ {
  //return $(this.textbox).width();

  /* grab the width of the textbox, and add the padding + borders because these
     aren't accounted for with width()
     TODO: the width should be grabbed by a JS property that includes padding/
           borders or the hardcoded 5 should be replaced with grabbing the elements
           padding + border
     */
  width = $(this.textbox).width();
  width += 5;
  return width;
};

/**
 * Handles three keydown events.
 * @scope private
 * @param oEvent The event object for the keydown event.
 */
AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {

    switch(oEvent.keyCode) {
        case 38: //up arrow
            this.previousSuggestion();
            break;
        case 40: //down arrow
            this.nextSuggestion();
            break;
        case 13: //enter
        case 27: //escape
            this.hideSuggestions();
            break;
    }
    return (oEvent.keyCode!=13);
};

/**
 * Handles keyup events.
 * @scope private
 * @param oEvent The event object for the keyup event.
 */
AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {

    var iKeyCode = oEvent.keyCode;

	timespan = oEvent.timeStamp - this.timestampEvent;
	this.timestampEvent = oEvent.timeStamp;
	timespanStart = oEvent.timeStamp - this.timestampStart;

	if ((timespan<1500) && (this.timestampStart>0) && (timespanStart<4000))	return;

	//if (this.timestampStart==0)

	this.timestampStart = oEvent.timeStamp;

    if ((iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123)) && iKeyCode != 8) return;
    //make sure not to interfere with non-character keys

//    eventGlobal = oEvent;

	//alert ('connection');

     this.provider.requestSuggestions(this, iKeyCode);
};

/**
 * Hides the suggestion dropdown.
 * @scope private
 */
AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

/**
 * Initializes the textbox with event handlers for
 * auto suggest functionality.
 * @scope private
 */
AutoSuggestControl.prototype.init = function () {

    //save a reference to this object
    var oThis = this;

	if (!this.textbox) return;

    //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);
    };

    //assign onkeydown event handler
    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
       return oThis.handleKeyDown(oEvent);
    };

    //assign onblur event handler (hides suggestions)
    this.textbox.onblur = function () {
        oThis.hideSuggestions();
    };

    //create the suggestions dropdown
    this.createDropDown();
};

/**
 * Highlights the next suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.nextSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;


    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
        var oNode = cSuggestionNodes[++this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;
    }
};

/**
 * Highlights the previous suggestion in the dropdown and
 * places the suggestion into the textbox.
 * @scope private
 */
AutoSuggestControl.prototype.previousSuggestion = function () {
    var cSuggestionNodes = this.layer.childNodes;

    if (cSuggestionNodes.length > 0 && this.cur > 0) {
        var oNode = cSuggestionNodes[--this.cur];
        this.highlightSuggestion(oNode);
        this.textbox.value = oNode.firstChild.nodeValue;
    }
};

/**
 * Selects a range of text in the textbox.
 * @scope public
 * @param iStart The start index (base 0) of the selection.
 * @param iLength The number of characters to select.
 */
AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {

    //use text ranges for Internet Explorer
    if (this.textbox.createTextRange) {
        var oRange = this.textbox.createTextRange();
        oRange.moveStart("character", iStart);
        oRange.moveEnd("character", iLength - this.textbox.value.length);
        oRange.select();

    //use setSelectionRange() for Mozilla
    } else if (this.textbox.setSelectionRange) {
        this.textbox.setSelectionRange(iStart, iLength);
    }

    //set focus back to the textbox
    this.textbox.focus();
};

/**
 * Builds the suggestion layer contents, moves it into position,
 * and displays the layer.
 * @scope private
 * @param aSuggestions An array of suggestions for the control.
 */
AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) {

    var oDiv = null;
    this.layer.innerHTML = "";  //clear contents of the layer

    for (var i=0; i < aSuggestions.length; i++) {
        oDiv = document.createElement("div");
		oDiv.appendChild(document.createTextNode(aSuggestions[i]));

		//oDiv2 = document.createElement("div");
		//oDiv2.appendChild(document.createTextNode("test"));

	    //oDiv.appendChild(oDiv2);

        this.layer.appendChild(oDiv);
    }

    this.layer.style.left = this.getLeft() + "px";
    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
	this.layer.style.width = this.getWidth() + "px";
    this.layer.style.visibility = "visible";

};

/**
 * Inserts a suggestion into the textbox, highlighting the
 * suggested part of the text.
 * @scope private
 * @param sSuggestion The suggestion for the textbox.
 */
AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {

    //check for support of typeahead functionality
    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
        var iLen = this.textbox.value.length;
        this.textbox.value = sSuggestion;
        this.selectRange(iLen, sSuggestion.length);
    }
};

/**
 * Highlights the given node in the suggestions dropdown.
 * @scope private
 * @param oSuggestionNode The node representing a suggestion in the dropdown.
 */
AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

function setOutput()
{
    if(http_request.readyState == 4)
    {
        if (http_request.status == 200)
        {
		  responseAjax = http_request.responseText;
		  ddv = document.getElementById('div_refresh');

		  ddv.innerHTML = responseAjax;
        }
        else
        {
		//  alert('There was a problem with the request.');
        }
    }
}

function setOutputImage()
{
  //alert(http_request_img.readyState);
    if(http_request_img.readyState == 4)
    {
	  if (http_request_img.status == 200)
	  {
		responseAjax = http_request_img.responseText;
		ddv = document.getElementById('floorplan');

		ddv.innerHTML = responseAjax;
	  }
	  else
	  {
	  //  alert('There was a problem with the request.');
	  }
    }
}

function setOutput2()
{
  aSuggestions = [];

  if(http_request.readyState == 4)
  {
	if (http_request.status == 200)
	{
	  responseAjax = http_request.responseText;

	  var pieces = responseAjax.split("|");

	  for(i=0 ; i<pieces.length ; i++)
	  {
		var p = trim(pieces[i]);
		if 	(p !='') aSuggestions.push(p);
	  }

	  //var iKeyCode = eventGlobal.keyCode;
	  //for backspace (8) and delete (46), shows suggestions without typeahead
	  //typeahead  = (iKeyCode != 8 && iKeyCode != 46);

	  typeahead = false;

	  suggestControl.autosuggest(aSuggestions, typeahead);
	}
	//else
	//{
	 // alert('There was a problem with the request.');
	//}
  }
}

function setOutput3()
{
  if(http_request.readyState == 4)
  {
	if (http_request.status == 200)
	{
	  response = http_request.responseText;

	  var first_split = response.split(">>");
	  var target = first_split[0];

	  dropdown = document.getElementById(target);
	  dropdown.options.length = 0;

	  if (first_split[1].length > 0)
	  {
		var pieces = first_split[1].split(":::");

		for (i = 0; i < pieces.length; i++)
		{
		  option_elements = pieces[i].split("|");
//		  alert(option_elements[0].replace(' ','&nbsp;'));
		  dropdown.options[dropdown.options.length] = new Option(option_elements[1], option_elements[0]);
		}
	  }
	  else
	  {
		dropdown.options[0] = new Option('', '');
	  }
	}
 	//else
	//{
	 // alert('There was a problem with the request.');
	//}
  }
}

function trim(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

function ConnectAjax(url, t)
{

  if (window.XMLHttpRequest) // Mozilla, Safari,...
  {
	if (t==4) http_request_img = new XMLHttpRequest();
	else http_request = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) // IE
  {
    if (t==4) http_request_img = new ActiveXObject("Microsoft.XMLHTTP");
	else http_request = new ActiveXObject("Microsoft.XMLHTTP");
  }

  if (t==1)
    http_request.onreadystatechange = setOutput;
  else if (t==4)
  {
    http_request_img.onreadystatechange = setOutputImage;
	http_request_img.open('GET', url, true);

	http_request_img.send(null);
	return;
  }
  else if (t==3)
    http_request.onreadystatechange = setOutput3;
  else
    http_request.onreadystatechange = setOutput2;

  http_request.open('GET', url, true);
  http_request.send(null);
}

function RefreshSuite(url, img)
{
  ConnectAjax(url, 1);
  ConnectAjax(img, 4);
}
