﻿/// <reference path="TVI.js" />


// Create WSN namespace
IPS = {};


// ********************************************* //
// *********** Testing purposes only *********** //
// ********************************************* //

TVI.apply(IPS, {

    /**
    * updateWatches
    */
    updateWatches: function() {

        $('#watchPanel').empty();

        var contents = '';
        
        // Add the search words
        
        contents += '<b>Words:</b><br />';
        contents += '<br />';
        contents += '<table class="watchPanelTable">';

        var wordsLength = IPS.searchWords.length;
        for (i = 0; i < wordsLength; i++) {

            contents += '<tr>';
            contents += '<td><b>' + IPS.searchWords[i].text + '</b></td>';
            contents += '<td>' + IPS.searchWords[i].startPosition + '</td>';
            contents += '</tr>';
        }

        contents += '</table>';
        
        contents += '<br />';
        contents += '<br />';
        
        // Add the search variables
        
        contents += '<table class="watchPanelTable">';
            contents += '<tr><td>Property Type:</td><td><b>' + IPS.currentSearch.propertyType + '</b></td></tr>';
            contents += '<tr><td>Bedrooms:</td><td><b>' + IPS.currentSearch.bedrooms + '</b></td></tr>';
            contents += '<tr><td>Location:</td><td><b>' + IPS.currentSearch.location + '</b></td></tr>';
            contents += '<tr><td>Location Rest:</td><td><b>' + IPS.currentSearch.locationRest + '</b></td></tr>';
            contents += '<tr><td>Within:</td><td><b>' + IPS.currentSearch.within + '</b></td></tr>';
            contents += '<tr><td>Min Price:</td><td><b>' + IPS.currentSearch.costMin + '</b></td></tr>';
            contents += '<tr><td>Max Price:</td><td><b>' + IPS.currentSearch.costMax + '</b></td></tr>';
        contents += '</table>';
        
        contents += '<br />';
        contents += '<br />';

        contents += 'Cursor position: <b>' + IPS.searchCursorPosition + '</b><br />';
        contents += '<br />';
        contents += '<br />';
        contents += 'Total Locations: <b>' + IPS.mainLocationTooltip.itemCount + '</b><br />';
        contents += 'Location selected: <b>' + IPS.mainLocationTooltip.selected + '</b><br />';
        contents += 'Location highlighted: <b>' + IPS.mainLocationTooltip.highlighted + '</b><br />';
        contents += '<br />';
        contents += '<br />';
        contents += 'Location start: <b>' + IPS.locationStartPosition + '</b><br />';
        contents += 'Location end: <b>' + IPS.locationEndPosition + '</b><br />';
        contents += '<br />';
        contents += '<br />';
        contents += 'Messages: <b>' + IPS.messages + '</b><br />';
        contents += '<br />';
        
        // Add the contents to the watch panel
        $('#watchPanel').append(contents);



    }

});



// ********************************************* //
// ************* Search Box Stuff ************** //
// ********************************************* //

TVI.apply(IPS, {


    searchPropertyTypes: [
        "apartment",
        "studio",
        "penthouse",
        "maisonnette",
        "detached house",
        "semi-detached house",
        "mid-terraced house",
        "end-terraced house",
        "mews",
        "end mews",
        "town house",
        "cottage",
        "bungalow",
        "detached bungalow",
        "barn",
        "land",
        "office"
    ],
    
    
    searchPropertyTypesAliases: [
    
        ["barn", ["barn"]],
        ["office", ["office"]],
        ["land", ["land"]],
        
        ["flat", ["apartment", "studio", "penthouse", "maisonnette"]],
        ["apartment", ["apartment", "studio", "penthouse", "maisonnette"]],
        ["studio", ["studio"]],
        ["penthouse", ["penthouse"]],
        ["maisonnette", ["maisonnette"]],
        
        ["house", ["detached house", "semi-detached house", "mid-terraced house", "end terraced house", "town house", "mews", "end mews", "cottage", "bungalow", "detached bungalow"]],
        ["home", ["detached house", "semi-detached house", "mid-terraced house", "end terraced house", "town house", "mews", "end mews", "cottage", "bungalow", "detached bungalow"]],

        ["detached", ["detached house", "detached bungalow"]],
        ["detatched", ["detached house", "detached bungalow"]],
        ["detached house", ["detached house", "detached bungalow"]],
        ["detached home", ["detached house", "detached bungalow"]],
        ["detatched house", ["detached house", "detached bungalow"]],
        ["detatched home", ["detached house", "detached bungalow"]],
        
        ["semi", ["semi-detached house"]],
        ["semi-detached house", ["semi-detached house"]],
        ["semi detached house", ["semi-detached house"]],
        ["semi-detatched house", ["semi-detached house"]],
        ["semi detatched house", ["semi-detached house"]],
        
        ["terrace", ["mid-terraced house"], ["end-terraced house"]],
        ["terrace house", ["mid-terraced house"], ["end-terraced house"]],
        ["terraced house", ["mid-terraced house"], ["end-terraced house"]],
        ["mid terrace", ["mid-terraced house"]],
        ["mid terraced", ["mid-terraced house"]],
        ["mid-terrace", ["mid-terraced house"]],
        ["mid-terraced", ["mid-terraced house"]],
        ["end terrace", ["end-terraced house"]],
        ["end terraced", ["end-terraced house"]],
        ["end-terrace", ["end-terraced house"]],
        ["end-terraced", ["end-terraced house"]],
        
        ["mews", ["mews"]],
        ["end mews", ["end mews"]],
        ["end-mews", ["end mews"]],

        ["townhouse", ["town house"]],
        ["town house", ["town house"]],
        ["town-house", ["town house"]],
        
        ["cottage", ["cottage"]],
        
        ["bungalow", ["bungalow", "detached bungalow"]],
        ["detached bungalow", ["detached bungalow"]]

    ],
    
    
    
    searchLocationWords: [
        ["near",1,["near"],""],
        ["miles of ",2,["miles","of"],"m"],
        ["miles from",2,["miles","from"],"m"],
        ["kilometres of ",2,["kilometres","of"],"k"],
        ["kilometres from ",2,["kilometres","from"],"k"],
        ["km of ",2,["km","of"],"k"],
        ["km from ",2,["km","from"],"k"],
        ["close to ",2,["close","to"],""],
        [" in ",1,["in"],""]
    ],
    
    searchPriceUnderWords: [
        "less than",
        "cheaper than",
        "below",
        "under",
        "for"
    ],
    
    searchPriceOverWords: [
        "more than",
        "above",
        "over",
        "from",
        "at least"
    ],
    

    /* True when we're delaying checking of the search box contents, so we don't check after every letter  */
    searchBoxDelay: false,

    /* The current cursor position in the search box  */
    searchCursorPosition: 0,
    
    /* An array of words contained in the search phrase */
    searchWords: [],
    
    /* The sentence that has actually been typed */
    searchText: "",
    
    /* The sentence after it has been cleaned */
    searchTextClean: "",
    
    /* The current search that has been identified */
    currentSearch: {
        propertyType: undefined,
        bedrooms: undefined,
        within: undefined,
        location: undefined,
        costMin: undefined,
        costMax: undefined
    },
    
    /* Resets the current search parameters */
    clearCurrentSearch: function() {
        IPS.currentSearch.propertyType = undefined;
        IPS.currentSearch.bedrooms = undefined;
        IPS.currentSearch.within = undefined;
        IPS.currentSearch.location = undefined;
        IPS.currentSearch.costMin = undefined;
        IPS.currentSearch.costMax = undefined;
    },
    
    /* Gets the word number which contains the passed word */
    searchGetWordMatchPos: function(keyword) {
        
        // Loop through the search words
        var wordsLength = IPS.searchWords.length;
        for (i = 0; i < wordsLength; i++) {
            
            // Check to see if the word contains the passed keyword
            if (IPS.searchWords[i].text.indexOf(keyword) > -1   ){
                return i+1;
            }
        }
        
        // If the word isn't found then return 0
        return 0;
    },
    
    /* Inserts a location into the location word */
    insertLocation: function(locationName) {
        
        // Set the location keyword
        IPS.currentSearch.location = locationName;
        
        var searchText = IPS.searchText;
        
        // Get the text before and after the location
        var beforeLocation = IPS.searchText.substring(0,IPS.locationStartPosition);
        var afterLocation = IPS.searchText.substring(IPS.locationEndPosition+2);
        
        // Set the search box text to include the new location
        IPS.searchText = beforeLocation + locationName + " " + afterLocation;
        $('#searchBox').val(IPS.searchText);
        
        // Set the cursor position
        var cursorPos = beforeLocation.length + locationName.length;
        setCaretPosition('searchBox',cursorPos);
        
        // Set locationRest
        IPS.currentSearch.locationRest = IPS.searchText.substring(IPS.locationStartPosition);
        
    },

    /* Takes the contents of the search box and parses it */
    parseSearch: function() {

        // Turn multiple spaces into single spaces
        //IPS.searchText = IPS.searchText.replace(/[ ]{2,}/g, " ");

        // Right trim the string
        c = IPS.searchText.replace(/\s+$/, "");
        
        // Store a copy of the text with all special characters removed
        IPS.searchTextClean = IPS.searchText.replace(/[^0-9A-Za-z£ ]/g, "");
        
        // Clone the search text
        var tempText = IPS.searchText;

        // Clear the array
        IPS.searchWords = [];

        var currentPosition = 0;

        // While there are still spaces in the text grab the first word
        while (tempText.indexOf(" ") > -1) {

            // Create the new word
            var newWord = {};

            // Set the position of the first character in the word then update the current position with the first character in the next word
            newWord.startPosition = currentPosition;
            currentPosition += tempText.indexOf(" ") + 1;

            // Set the text of the word and remove unwanted characters
            newWord.text = tempText.substring(0, tempText.indexOf(" "));
            newWord.text = newWord.text.replace(/[^0-9A-Za-z£ ]/g, "");

            // Add the word to the word array
            IPS.searchWords.push(newWord);

            // Remove the parsed text
            tempText = tempText.substring(tempText.indexOf(" ") + 1);

        }

        // When there are no spaces left get the last word
        var newWord = {};

        // Set the position of the first character in the word
        newWord.startPosition = currentPosition;

        newWord.text = tempText;
        newWord.text = newWord.text.replace(/[^0-9A-Za-z£ ]/g, "");

        // Add the word to the word array
        IPS.searchWords.push(newWord);
        
        
        
        
        // ********************************************* //
        // ************* Property Types **************** //
        // ********************************************* //

        // Check all the property types
        var propertyTypesLength = IPS.searchPropertyTypesAliases.length;
        for (i = 0; i < propertyTypesLength; i++) {

            // Check to see if the property type is in the sentence
            if (IPS.searchText.indexOf(IPS.searchPropertyTypesAliases[i][0]) > -1   ){
            
                var types = '';
                var typesLength = IPS.searchPropertyTypesAliases[i][1].length;
                
                for (j = 0; j < typesLength; j++) {
                    types += IPS.searchPropertyTypesAliases[i][1][j] + ',';
                }
                
                IPS.currentSearch.propertyType = types;
            }

        }
        
        
        // ********************************************* //
        // ************* Bedrooms ********************** //
        // ********************************************* //
        
        // Check to see if the user has entered a number of bedrooms
        if (IPS.searchText.indexOf("bedroom") > -1){
            
            // Get the word number that matches "bedroom"
            var keywordWordPosition = IPS.searchGetWordMatchPos("bedroom");
            
            // Get the word before it
            var bedroomsWord = IPS.searchWords[keywordWordPosition-2].text;
            
            // Set the number of bedrooms
            IPS.currentSearch.bedrooms = bedroomsWord;
        }
        

        
        // ********************************************* //
        // ************* Distance ********************** //
        // ********************************************* //

        IPS.locationStartPosition = -1;
        IPS.locationEndPosition = -1;

        // Check to see if the user has entered a location and "within" distance
        var locationWordsLength = IPS.searchLocationWords.length;
        for (k = 0; k < locationWordsLength; k++) {

            // Check to see if the keyword is in the sentence
            if (IPS.searchText.indexOf(IPS.searchLocationWords[k][0]) > -1   ){
                
                // Set up some variables
                var phrase = IPS.searchLocationWords[k][0];
                var wordsInPhrase = IPS.searchLocationWords[k][1];
                var lookingForWord = 1;
                var firstWordIndex = 0;
                
                // Start with the first word and attempt to find the position of the first word in the phrase
                var searchWordsLength = IPS.searchWords.length;
                for (l = 0; l < searchWordsLength; l++) {
                    
                    // See if the word matches the word we are looking for
                    if(IPS.searchWords[l].text === IPS.searchLocationWords[k][2][lookingForWord-1]){
                        
                        // If it is the last word in the phrase
                        if(wordsInPhrase === lookingForWord){
                            
                            // Track back and set the index of the first word in the phrase
                            firstWordIndex = (l+1)-wordsInPhrase;
                        }
                        else{
                            lookingForWord++;
                        }
                        
                    }
                    else {
                        lookingForWord = 1
                    }
                    
                }
                
                // Update the location variable and location start and end positions
                IPS.currentSearch.location = IPS.searchWords[firstWordIndex+wordsInPhrase].text;
                IPS.locationStartPosition = IPS.searchWords[firstWordIndex].startPosition + IPS.searchLocationWords[k][0].trim().length + 1;
                IPS.locationEndPosition = IPS.locationStartPosition + IPS.searchWords[firstWordIndex+wordsInPhrase].text.length-1;
                IPS.currentSearch.locationRest = IPS.searchText.substring(IPS.locationStartPosition);

                // Work out the within value
                switch(phrase){
                    case " in ":
                      IPS.currentSearch.within = 2;
                      break;    
                    case "near":
                      IPS.currentSearch.within = 5;
                      break;
                    case "close to":
                      IPS.currentSearch.within = 5;
                      break;
                    default:
                      IPS.currentSearch.within = IPS.searchWords[firstWordIndex-1].text;
                }
            }
        }
        
        
        // ********************************************* //
        // *********** Location Tool Tip *************** //
        // ********************************************* //
        
        // Check to see if we are currently typing the location
        
        if(IPS.searchCursorPosition > IPS.locationStartPosition && IPS.searchCursorPosition <= IPS.locationEndPosition + 1 && IPS.searchCursorPosition !== 0){
        
            // Check to see if the tooltip is already displayed
            if(!IPS.mainLocationTooltip.isVisible()){
                IPS.mainLocationTooltip.show();
            }
            
            // Reposition the tooltip
            IPS.mainLocationTooltip.reposition();
            
            // Get new items and update the tooltip
            IPS.mainLocationTooltip.getItems(IPS.currentSearch.location);
        }
        else{
            IPS.mainLocationTooltip.hide()
        }
        
        
        // ********************************************* //
        // *************** Prices ********************** //
        // ********************************************* //
        
        // Find words which are prices
        var priceWords = [];
        var searchWordsLength = IPS.searchWords.length;
        
        // Loop through al the words in the sentence
        for (m = 0; m < searchWordsLength; m++) {
            
            // Check to see if the word starts with a £ symbol
            if(IPS.searchWords[m].text.indexOf("£") === 0){
                IPS.searchWords[m].text = IPS.searchWords[m].text.replace("£","");
                IPS.searchWords[m].text = IPS.searchWords[m].text.replace("k","000");
                priceWords.push(m);
            }
            // Or check to see if it ends with a k
            else if(IPS.searchWords[m].text.length !== 0 && IPS.searchWords[m].text.indexOf("k") === IPS.searchWords[m].text.length -1){
                
                // Check to see if it is otherwise numeric
                var kWord = IPS.searchWords[m].text.substring(0,IPS.searchWords[m].text.length -1);
                if(!isNaN(kWord)){
                    IPS.searchWords[m].text = IPS.searchWords[m].text.replace("k","000");
                    priceWords.push(m);
                }
            }
            // otherwise check to see if it is numeric and over 10000
            else if(!isNaN(IPS.searchWords[m].text) && IPS.searchWords[m].text > 9999){
                priceWords.push(m);
            }
        }
        
        // Check that at least one price has been found
        if(priceWords.length > 0){
            
            // Loop through all the prices that have been found
            var priceWordsLength = priceWords.length;
            for (n = 0; n < priceWordsLength; n++) {
                
                // Get the position of the price word
                var pricePosition = IPS.searchWords[priceWords[n]].startPosition;
                
                // Get the search text that appears before the price
                var textBefore = IPS.searchText.substring(0,pricePosition-1);
                
                // Loop through all of the "before price" phrases that may indicate "under"
                var underWordsLength = IPS.searchPriceUnderWords.length;
                for (p = 0; p < underWordsLength; p++) {
                    
                    // Get the length of the word
                    var wordLength = IPS.searchPriceUnderWords[p].length;
                    
                    // Get that number of characters from before the price
                    var charsBefore = textBefore.substring(textBefore.length-wordLength);
                    
                    // See if there is a match
                    if(charsBefore === IPS.searchPriceUnderWords[p]){
                        IPS.currentSearch.costMax = IPS.searchWords[priceWords[n]].text;
                    }
                    
                }
                
                // Loop through all of the "before price" phrases that may indicate "over"
                var overWordsLength = IPS.searchPriceOverWords.length;
                for (q = 0; q < overWordsLength; q++) {
                    
                    // Get the length of the word
                    var wordLength = IPS.searchPriceOverWords[q].length;
                    
                    // Get that number of characters from before the price
                    var charsBefore = textBefore.substring(textBefore.length-wordLength);
                    
                    // See if there is a match
                    if(charsBefore === IPS.searchPriceOverWords[q]){
                        IPS.currentSearch.costMin = IPS.searchWords[priceWords[n]].text;
                    }
                    
                }
                
            }
        }

    }  

});


// ********************************************* //
// *************** Tooltip Stuff *************** //
// ********************************************* //

IPS.locationTip = function(config) {
    
    var defaults = {};
    
    // Apply config
    TVI.apply(this, config, defaults);
    
    // Create unique id if one doesn't already exist
    TVI.createID(this);
    
    // Register with the component manager
    TVI.ComponentManager.register(this.id, this);
    
    this.init();
    
    
};

IPS.locationTip.prototype = {

    startPosition: 0,
    selected: -1,
    highlighted: -1,
    visible: false,
    
    items: [],
    
    init: function(){
    
        var component = this;
    
        // Add click events to the drop down list
        $('LI', component.element).live('click', function(){
                    
            var itemText = $(this).find('SPAN').text();
            
            (function(){
                IPS.insertLocation(itemText);
                component.hide();
            })()
            
        });
    
    },
    
    
    // Re-inserts the items in the list
    drawList: function(startPosition){
        
        var component = this;
        
        var spans = $('LI SPAN', component.element);
        var currentPosition = startPosition;
        
        // Put correct text in the list
        for(i=0; i < 5; i++){
            var itemText = component.items[currentPosition] || "";
            spans.eq(i).html(itemText);
            currentPosition++;
            
            // Get the list item
            var listItem = $('LI', component.element).eq(i);
            
            // Check to make sure the item is not blank
            if(itemText !== ""){
            
                // Add hover and click events
                $('LI', component.element).eq(i).hover(function(){
                    $(this).addClass("hover");
                }, function(){
                    $(this).removeClass("hover");
                });
                
            }
        }
        
    },
    
    
    // Draw the list with no suggestions
    noSuggestions: function(){
        
        var component = this;
        
        component.reset();
        
        var spans = $('LI SPAN', component.element);
        spans.eq(0).html("No Suggestions...");

    },
    
    // Clears the list and removes highlighting
    reset: function(){
        
        var component = this;
        
        // Re-create the list
        component.element.empty();
        component.element.append('<li class="first"><span></span></li><li><span></span></li><li><span></span></li><li><span></span></li><li class="last"><span></span></li>');
        
        // Set the state
        component.startPosition = 0;
        component.selected = -1;
        component.removeHighlight();  
    },
    
    // Gets new items for the list
    getItems: function(letters){
        
        var component = this;
        
        var jsonData='';
        jsonData += '{"config":{';
        jsonData += '"query":"getLocations"';
        jsonData += ',"parameters":"{';
        jsonData += '\\"letters\\":\\"' + letters + '%\\"';
        jsonData += '}"}}';
        
        TVI.ajax({
            url: "Handlers/Data.aspx/getRecords",
            data: jsonData,
            success: function(response){
                
                // Clear the items array
                component.items = [];
                
                // Loop through the locations returned and add them
                var locationsCount = response.records.length;
                for(i=0; i < locationsCount; i++){
                    component.items.push(response.records[i][0]);
                }

                // TEST
                IPS.mainLocationTooltip.itemCount = component.items.length;

                // Check to see if any items were returned
                if(component.items.length > 0){
                    component.drawList(0);
                    component.selected = 0;
                    component.setHighlight(0);  
                }
                else{
                    component.noSuggestions();
                }
                
                component.startPosition = 0;
                
            }
        });
        
    },
    
    // Changes which item is highlighted
    setHighlight: function(itemNumber){
        $('LI', this.element).removeClass('selected').eq(itemNumber).addClass('selected');
        this.highlighted = itemNumber;
    },
    
    // Removes highlighting
    removeHighlight: function(){
        $('LI', this.element).removeClass('selected');
        this.highlighted = -1;
    },

    // Shows the toolTip
    show: function(){
    
        if (navigator.userAgent.indexOf("MSIE 6") < 0 ){
            this.reposition();
            this.element.show();
            this.visible = true;
        }
    },
    
    // Repositions the toolTip
    reposition: function(){

        var searchBox = $('#searchBox')
        var searchBoxOffset = searchBox.offset();
        var searchBoxLength = searchBox.val().length;
        
        var xPos = searchBoxOffset.left -110 + (searchBoxLength * 10);
        var yPos = searchBoxOffset.top +32;
        
        this.element.css({
            left: xPos,
            top: yPos
        });
        
    },
    
    // Hides the toolTip
    hide: function(){
        this.element.hide();
        this.visible = false;
    },
    
    // Returns true if the tip is currently visible
    isVisible: function(){
        if (this.visible === true){
            return true;
        }
        else{
            return false;
        }
    },
    
    // Fires when the list is scrolled up
    up: function(){
        
        var component = this;
        
        // Check to see if it's possible to move up
        if(component.selected > 0){
            
            component.selected--;
            
            // If we're not already highlighting the 1st item
            if(component.highlighted > 0){
                component.highlighted--;
                component.setHighlight(component.highlighted);
            }
            else { //If we're already highlighting the first item
                component.startPosition--;
                component.drawList(component.startPosition);
            }
        }
    },
    
    // Fires when the list is scrolled up
    down: function(){
        
        var component = this;
        
        // Check to see if it's possible to move down
        if(component.selected < component.items.length -1){
            
            component.selected++;
            
            // If we're not already highlighting the 5th item
            if(component.highlighted < 4){
                component.highlighted++;
                component.setHighlight(component.highlighted);
            }
            else { //If we're already highlighting the last item
            
                component.startPosition++;
                component.drawList(component.startPosition);
            }
        }
    },
    
    // Fires when an item is selected
    itemSelected: function(){
    
        IPS.insertLocation(this.items[this.selected]);
    }
    

};



// Check that the page has loaded
$(document).ready(function() {

    // Create the location tooltip
    IPS.mainLocationTooltip = new IPS.locationTip({
        element: $('#locationTip')
    });   

    // Fire this when a key is lifted
    $('#searchBox').keyup(function(e) {
    
        e.preventDefault();

        /***** Start a timer *****/
        TVI.logTimer("keyPress");
        
        // Check the key that was clicked
        switch(e.keyCode){
            case 38: // Up Key
                IPS.mainLocationTooltip.up();
                return false;
            case 40: // Down Key
                IPS.mainLocationTooltip.down();
                return false;
            case 13: // Enter Key
            
                // Check to see if the location tip is currently being displayed
                if(IPS.mainLocationTooltip.isVisible()){
                    IPS.mainLocationTooltip.itemSelected();
                    IPS.mainLocationTooltip.hide();
                }
                else{
                    submit();
                }
                return false;
            default:
                // Update the cursor position
                IPS.searchCursorPosition = doGetCaretPosition(document.getElementById('searchBox'));
                
                // Clear the current search parameters
                IPS.clearCurrentSearch();
                
                // Set the text that was typed
                IPS.searchText = $(this).val();

                // Parse the search text - send it the current contents
                IPS.parseSearch();
                break;
        }

        /***** End the timer *****/
        TVI.logTimerEnd("keyPress");
        
        return false;

    });
    
    
    
    // ********************************************* //
    // ******** Testing purposes only ************** //
    // ********************************************* //

    // var watchPanel = $('<div id="watchPanelWrapper" style="position:fixed; top:10px; right:10px; width:300px; height:700px; font-size:10px; font-family:arial; background:black;"><div id="watchPanel" style="margin:10px; overflow:auto; color:white; font-size:12px;"></div></div>');
    // $('body').append(watchPanel);

    // window.setInterval('IPS.updateWatches()', 500);
    // ********************************************* //
    
    
    $('#intelliSearch .go').click(submit);
    

});



function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}


var submit = function(){

    var url = 'main.aspx';
    
    var args = '';
    
    if (IPS.currentSearch.propertyType){ args += '&type=' + IPS.currentSearch.propertyType; }
    if (IPS.currentSearch.location){ args += '&location=' + IPS.currentSearch.locationRest; }
    if (IPS.currentSearch.bedrooms > 0){ args += '&bedrooms=' + IPS.currentSearch.bedrooms; }
    if (IPS.currentSearch.costMin > 0){ args += '&minprice=' + IPS.currentSearch.costMin; }
    if (IPS.currentSearch.costMax > 0){ args += '&maxprice=' + IPS.currentSearch.costMax; }
    
    if (args.length > 0){ url += '?page=search' +  args; }
    
    //log search
    TVI.ajax({
    
        url: 'Handlers/IPS.Searches.aspx/logSearch',
        data: '{ \"keywords\": \"' + $('#searchBox').val() + '\" }',
        success: function(){
            window.location = url;
        },
        failure: function(){
            window.location = url;
        },
        error: function(){
            window.location = url;
        }
    
    });

};


//currentSearch: {
//        propertyType: undefined,
//        propertySubType: undefined,
//        bedrooms: undefined,
//        within: undefined,
//        location: undefined,
//        costMin: undefined,
//        costMax: undefined
//    },

function doGetCaretPosition (ctrl) {
    var CaretPos = 0;
    
    // IE Support
    if (document.selection) {

        ctrl.focus ();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart ('character', -ctrl.value.length);
        CaretPos = Sel.text.length - SelLength;
    }
    
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0'){
        CaretPos = ctrl.selectionStart;
    }
    
    return (CaretPos);

}
