﻿
$(function() {

    //debugger;

    var objDiv = $("<div class='outputTest' style='display:none;'></div>");
    var iframe = $('<IFRAME style="DISPLAY: none; LEFT: 0px; POSITION: absolute; TOP: 0px; height: 900px; width: 200px; background-color:#777;  filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=100)"  src="javascript:false;" frameBorder="1" scrolling="no"></IFRAME>');
    var input = $("#hsLocation, #PreownedHomeSearchPanel1_hsLocation");
    input.after(objDiv);

    // variables which keep the log of the sizes and index's of the
    // list elements =]
    var currentSelectedResult = 0;
    var currentSize = 0;
    var devEnv = true;
    var currentId = "hsLocation";
    // 8 seconds to timeout =]
    var timeoutTime = 8000;
    var timedOut = true;

    // depending on the addRemove boolean value will deturmine
    // if the element index class will be added or removed =]
    function selectedKeyword(index, addRemove) {
        var obj = objDiv.find("ul li");
        if (!addRemove) {
            obj.eq(index).addClass("lists-hover");
        } else {
            obj.eq(index).removeClass("lists-hover");
        }
    }

    // when event is triggered this function will hide the results
    function hideKeywords(localTimeout) {
        setTimeout(hideDropDown, localTimeout || timeoutTime);
    }

    // to clear the users selected value =]
    function clearSelectedValues() {
        objDiv.find("ul li").each(function() {
            $(this).removeClass("lists-hover");
        });
    }

    // move the selected result up or down =]
    function move(direction) {
        var moveDir = (direction == "up") ? true : false;

        if (currentSelectedResult > currentSize) {
            currentSelectedResult = 0;
        }

        if (moveDir) {
            if (currentSelectedResult > 0) {
                selectedKeyword((currentSelectedResult - 1), false);
                selectedKeyword(currentSelectedResult, true);

                currentSelectedResult--;
            }
        } else {
            if (currentSelectedResult < (currentSize - 1)) {
                selectedKeyword((currentSelectedResult + 1), false);
                selectedKeyword(currentSelectedResult, true);

                currentSelectedResult++;
            }
        }
    }

    //uses liElement (the current selected element? as a jQuery object) as the current selection
    function selectItem(liElement) {
        if (!liElement) return;
        var keywords = document.getElementById(currentId);

        keywords.value = liElement.html();

        $("#GMapLng").val(liElement.data("Longitude"));
        $("#GMapLat").val(liElement.data("Latitude"));
    }

    function hideDropDown() {
        objDiv.hide();
        objDiv.children("ul").remove();
        iframe.hide();
    }


    // when the user presses enter in focus of the text box
    // the current value which they've selected is returned =]
    function getCurrentKeyword() {
        if (currentSize > 0) {
            var curVal = objDiv.find("ul li").eq(currentSelectedResult);

            if (curVal != "" && curVal != null) {
                selectItem(curVal);
            }

            currentSize = 0;
            currentSelectedResult = 0;
            hideDropDown();

            return false;
        }
    }

    // is the keyword returning no results? =]
    function matchingResults(keyword) {
        return (keyword == "Sorry, no matching results");
    }

    // handles the error output =]
    function Error(XMLHttpRequest, textStatus, errorThrown) {
        alert("ERROR: " + XMLHttpRequest + " " + textStatus);
    }

    // handles the success web script =]
    function Success(xml, textStatus) {
        hideDropDown();

        currentSize = xml.length;
        objDiv.show();

        var outputHTML = $("<ul></ul>");
        if (xml.length > 0) {
            // output the values from the string array =]
            for (var i = 0; i < xml.length; i++) {
                var current = xml[i];
                $("<li>" + current.Name + "</li>")
                    .data("Latitude", current.Latitude)
                    .data("Longitude", current.Longitude)
                    .appendTo(outputHTML);
            }
        } else {
            outputHTML.append("<li>Sorry, no matching results</li>");
            hideKeywords(3000);
        }

        //outputHTML += "</ul>";

        objDiv.append(outputHTML);

        // when the list has been created, the events are needed for the
        // elements =]
        objDiv.find("ul li")
                    .hover(function() {
                        clearSelectedValues();

                        if (!matchingResults(this.innerHTML)) {
                            $(this).addClass("lists-hover");
                        }
                    })
                    .mouseout(function() {
                        if (!matchingResults(this.innerHTML)) {
                            $(this).removeClass("lists-hover");
                        }
                    })
                    .click(function() {
                        if (!matchingResults(this.innerHTML)) {
                            selectItem($(this));

                            currentSize = 0;
                            currentSelectedResult = 0;
                            hideDropDown();
                        }
                    });

        // has the object got a size to it? =]
        if (currentSize > 0) {
            selectedKeyword(currentSelectedResult, false);
            timedOut = false;
        }

        doNastyIe6Hack(objDiv,outputHTML);
    }

    function doNastyIe6Hack(objDiv, outputHTML) {
        if (!($.browser.msie && (/6.0/g).test(navigator.userAgent))) return;
        var left = 0;
        input.prevAll().filter(function() { return $(this).css("float") == "left" }).each(function(e) { left += $(this).width(); });
        var $ouputTest = objDiv;
        var pos = $ouputTest.position();
        iframe.css({ top: pos.top + "px", left: pos.left + left + "px", display: "block", height: outputHTML.height() + "px" });
        iframe.appendTo(objDiv.parent());
    }

    var timeout;
    // when the user then pressed a key =]
    $("#hsLocation, #PreownedHomeSearchPanel1_hsLocation")
    .blur(function(e) { if (e.keyCode == 9) { hideDropDown(); } else { hideKeywords(500); } })
    .keyup(function(e) {
        switch (e.keyCode) {

            case 38:
                move("up");
                break;
            case 40:
                move("down");
                break;
            case 13:
                return getCurrentKeyword();

                break;
            default:
                var curID = $(this).attr("id");

                if (curID == "PreownedHomeSearchPanel1_hsLocation") {
                    devEnv = false;
                    currentId = $(this).attr("id");
                }

                if (this.value.length >= 3 && this.value.length <= 50) {
                    var keyword = this.value;


                    clearTimeout(timeout);
                    // add the time delay of 300 miliseconds =]
                    timeout = setTimeout(function() {
                        // send the magic to the web service =]
                        $.ajax({
                            type: "POST",
                            url: websitePath + "AutoComplete.asmx/AutoCompleteReturn",
                            data: '{"keyword" : "' + keyword.toString() +
                                  '", "searchDev" : "' + devEnv.toString() + '"}',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            error: Error,
                            success: Success
                        });
                    }, 300);
                } else {
                    hideDropDown();
                }
                break;
        }
    });

    objDiv.mouseout(function() {
        if (!timedOut) {
            hideKeywords();
        }

        timedOut = true;
    });
    // the below is for a feature for the new developments search
    //$("li #dsIncComingSoon").change(function() {
    //    if ($(this).is(":checked")) {
    //        devEnv = true;
    //    } else {
    //        devEnv = false;
    //    }
    //});
});
