﻿function SetSearchControls()
{
    var searchTerm = "";
    var locationTerm = "";
    // waiting for a url like:
    // /suche/?q=test&loc=loc
    var params = qs();
    // split the url
    var key = null;
    var itemsFound = 0;
    for (var key in params)
    {
        switch (key) {
            case "loc":
                $('#tbxLocation').val(decodeURI(params[key]));
                itemsFound++;
                break;
            case "q":
                $('#tbxQuery').val(decodeURI(params[key]));
                itemsFound++;
                break;
            default:
                break;
        }
        if (itemsFound >= 2) {
            break;
        }
    }
};

function qs() {
    var qsParm = new Array();
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) 
    {
        var pos = parms[i].indexOf('=');
        if (pos > 0) 
        {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }
    return qsParm;
};

function InitSiteSearch(_setControls) {
    RegCtrls();
    if (_setControls) SetSearchControls();

    //    $('#tbxSearchTerm').suggest({
    //        jsonUrl: '/handlers/SearchSuggestHandler.ashx',
    //        minChars: 3,
    //        maxHeight: 200,
    //        width: 300,
    //        docache: false,
    //        popupID: 'divSuggest',
    //        cssClass: 'suggest',
    //        queryTimeout: 300
    //    });
};

function DoSiteSearch()
{
    var fullUrl = "";
    var baseUrl = "/suche/";
    var qVal = $('#tbxQuery').val();
    var locVal = $('#tbxLocation').val();
    fullUrl = baseUrl + '?q=' + SecureEncode(qVal) + '&loc=' + SecureEncode(locVal);
    //console.log('URL:' + fullUrl);
    window.location = fullUrl;
    return false;
};

function SecureEncode(_val) {
    if (_val != null && _val != '') 
    {
        return encodeURI(_val);
    }
    return '';
};

function RegCtrls() {
    Reg13('tbxQuery');
    Reg13('tbxLocation');
};


function Reg13(_id) {
    var ctrlID = '#' + _id;
    $(ctrlID).keyup(function (event) {
        if (event.keyCode == '13') {
            event.preventDefault();
            DoSiteSearch();
        }
    });
};



function ResolveURL(_url)
{
    return BASE_URL + _url;
}


if (!this.JSON)
{
    JSON = {};
}
(function()
{

    function f(n)
    {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function')
    {

        Date.prototype.toJSON = function(key)
        {

            return this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function(key)
        {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string)
    {

        // If the string contains no control characters, no quote characters, and no
        // backslash characters, then we can safely slap some quotes around it.
        // Otherwise we must also replace the offending characters with safe escape
        // sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function(a)
            {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder)
    {

        // Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        // If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function')
        {
            value = value.toJSON(key);
        }

        // If we were called with a replacer function, then call the replacer to
        // obtain a replacement value.

        if (typeof rep === 'function')
        {
            value = rep.call(holder, key, value);
        }

        // What happens next depends on the value's type.

        switch (typeof value)
        {
            case 'string':
                return quote(value);

            case 'number':

                // JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

                // If the value is a boolean or null, convert it to a string. Note:
                // typeof null does not produce 'null'. The case is included here in
                // the remote chance that this gets fixed someday.

                return String(value);

                // If the type is 'object', we might be dealing with an object or an array or
                // null.

            case 'object':

                // Due to a specification blunder in ECMAScript, typeof null is 'object',
                // so watch out for that case.

                if (!value)
                {
                    return 'null';
                }

                // Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

                // Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]')
                {

                    // The value is an array. Stringify every element. Use null as a placeholder
                    // for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1)
                    {
                        partial[i] = str(i, value) || 'null';
                    }

                    // Join all of the elements together, separated with commas, and wrap them in
                    // brackets.

                    v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

                // If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object')
                {
                    length = rep.length;
                    for (i = 0; i < length; i += 1)
                    {
                        k = rep[i];
                        if (typeof k === 'string')
                        {
                            v = str(k, value);
                            if (v)
                            {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else
                {

                    // Otherwise, iterate through all of the keys in the object.

                    for (k in value)
                    {
                        if (Object.hasOwnProperty.call(value, k))
                        {
                            v = str(k, value);
                            if (v)
                            {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

                // Join all of the member texts together, separated with commas,
                // and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

    // If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function')
    {
        JSON.stringify = function(value, replacer, space)
        {

            // The stringify method takes a value and an optional replacer, and an optional
            // space parameter, and returns a JSON text. The replacer can be a function
            // that can replace values, or an array of strings that will select the keys.
            // A default replacer method can be provided. Use of the space parameter can
            // produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

            // If the space parameter is a number, make an indent string containing that
            // many spaces.

            if (typeof space === 'number')
            {
                for (i = 0; i < space; i += 1)
                {
                    indent += ' ';
                }

                // If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string')
            {
                indent = space;
            }

            // If there is a replacer, it must be a function or an array.
            // Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number'))
            {
                throw new Error('JSON.stringify');
            }

            // Make a fake root object containing our value under the key of ''.
            // Return the result of stringifying the value.

            return str('', { '': value });
        };
    }


    // If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function')
    {
        JSON.parse = function(text, reviver)
        {

            // The parse method takes a text and an optional reviver function, and returns
            // a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key)
            {

                // The walk method is used to recursively walk the resulting structure so
                // that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object')
                {
                    for (k in value)
                    {
                        if (Object.hasOwnProperty.call(value, k))
                        {
                            v = walk(value, k);
                            if (v !== undefined)
                            {
                                value[k] = v;
                            } else
                            {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


            // Parsing happens in four stages. In the first stage, we replace certain
            // Unicode characters with escape sequences. JavaScript handles many characters
            // incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text))
            {
                text = text.replace(cx, function(a)
                {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            // In the second stage, we run the text against regular expressions that look
            // for non-JSON patterns. We are especially concerned with '()' and 'new'
            // because they can cause invocation, and '=' because it can cause mutation.
            // But just to be safe, we want to reject all unexpected forms.

            // We split the second stage into 4 regexp operations in order to work around
            // crippling inefficiencies in IE's and Safari's regexp engines. First we
            // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
            // replace all simple value tokens with ']' characters. Third, we delete all
            // open brackets that follow a colon or comma or that begin the text. Finally,
            // we look to see that the remaining characters are only whitespace or ']' or
            // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '')))
            {

                // In the third stage we use the eval function to compile the text into a
                // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                // in JavaScript: it can begin a block or an object literal. We wrap the text
                // in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

                // In the optional fourth stage, we recursively walk the new structure, passing
                // each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }

            // If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
} ());


var s3c = {};
s3c.lunchpin = function() { };
s3c.lunchpin.controls = function() { };
s3c.lunchpin.views = function() { };

$.extend({ URLEncode: function(c)
{
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length)
    {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '')
        {
            o += m[1]; x += m[1].length;
        } else
        {
            if (c[x] == ' ') o += '+'; else
            {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        }
    } return o;
},
    URLDecode: function(s)
    {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '')
        {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});




(function($)
{
    $.fn.bindTo = function(data, options)
    {
        var defaults = {
            appendTo: null,
            fillTo: null,
            root: 'data',
            onBind: null,
            onBound: null,
            fill: false
        }
        var options = $.extend(defaults, options);

        if ($.isFunction(options.onBind))
            options.onBind();
        //var template = '<!--bind.template-->' + ((options.fill) ? this.html() : this.parent().html()).replace(/%7B/g, '{').replace(/%7D/g, '}') + '<!--bind.template-->';
        var template = '<!--bind.template-->' + this.html().replace(/%7B/g, '{').replace(/%7D/g, '}') + '<!--bind.template-->';
        var repeaters = this.bindTo.findRepeaters(template);
        var fixedData = {};
        fixedData[options.root] = data;
        var content = this.bindTo.traverse(
									  'bind.template',
									  fixedData,
									  repeaters['<!--bind.template-->'].template,
									  repeaters,
									  'bind.template'
									 );
        if (options.fill)
            this.html(content);
        if (options.appendTo != null)
            content = $(content).appendTo($(options.appendTo));
        if (options.fillTo != null)
            $(options.fillTo).html(content);
        if ($.isFunction(options.onBound))
            options.onBound(content, data);
        return content;
    }
    $.extend($.fn.bindTo,
	{
	    templates: {},
	    traverse: function(key, data, template, repeaters, parent)
	    {
	        if (typeof data == 'string' || typeof data == 'number' || typeof data == 'boolean')
	        {
	            return template.replace(new RegExp("\{" + key + "\}", "ig"), data);
	        } else if (typeof data == 'object')
	        {
	            if (typeof data.length == 'undefined')
	            {
	                if (repeaters['<!--' + parent + '-->'].action)
	                    template = $.fn.bindTo[repeaters['<!--' + parent + '-->'].action](template, data) || template;
	                for (var item in data)
	                {
	                    if (typeof data[item] == 'object')
	                    {
	                        if (typeof repeaters['<!--' + item + '-->'] != 'undefined')
	                        {//Skip not defined templates for child in aggregate object
	                            var temp = $.fn.bindTo.traverse(item, data[item], repeaters['<!--' + item + '-->'].template, repeaters, item);
	                            template = template.replace('<!--' + item + '-->', temp);
	                        }
	                    } else
	                    {
	                        var temp = $.fn.bindTo.traverse(item, data[item], template, repeaters);
	                        template = temp;
	                    }
	                }
	                return template;
	            } else
	            {
	                var listTemplate = '';
	                for (var item in data)
	                {
	                    listTemplate += $.fn.bindTo.traverse(item, data[item], repeaters['<!--' + key + '-->'].template, repeaters, key);
	                }
	                return listTemplate;
	            }
	        }
	        return ''; //(handle extjs) this will return '' for function in case you extned array or object
	    },
	    findRepeaters: function(template)
	    {
	        $this = this;
	        var templates = {};
	        var reg = new RegExp('<!--[.a-zA-Z1-9]*-->', 'g');
	        var regAction = new RegExp('<!--action:[$.a-zA-Z1-9]*-->', 'g');
	        var matches = (template.match(reg));
	        $.each(matches,
				   function()
				   {
				       if (templates[this] != undefined)/*template is already added because end tag and start tags are the same*/
				           return true;
				       templates[this] = {};
				       var temp = template.substring(template.indexOf(this) + this.length, template.lastIndexOf(this));
				       var innerMatches = (temp.match(reg)) || [];
				       $.each(innerMatches,
							   function()
							   {
							       if (temp.indexOf(this) > -1)
							       {
							           var innerRepeater = temp.substring(temp.indexOf(this), temp.lastIndexOf(this) + this.length);
							           temp = temp.replace(innerRepeater, this);
							       }
							   }
						)
				       var actions = (temp.match(regAction)) || [];
				       var key = this;
				       $.each(actions,
							   function()
							   {
							       var action = this.substring(11, this.length - 3);
							       templates[key].action = action;
							       temp = temp.replace(actions, '');
							   }
						)
				       templates[this].template = temp;
				   }
			)
	        return templates;
	    }
	}
);
    //
})(jQuery);


var mapObj = null;
var geocoderObj = null;
var hfLat = null;
var hfLon = null;
var currentLat = null;
var currentLon = null;
var currentLoc = null;
var pinUrl = null;
var pinLBUrl = null;
var currentPinImage = null;
var currentPin = null;
var pinList = [];
var infowindow = null;
var lastList = null;

var locationPin = null;

function InitMapping(_canvasID)
{

    var myLatlng = new google.maps.LatLng(47.5, 13.3);
    var myOptions = {
        zoom: 6,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    mapObj = new google.maps.Map(document.getElementById(_canvasID), myOptions);

    infowindow = new google.maps.InfoWindow({ content: "holding..." });

    pinUrl = ResolveURL('/images/pins/pin_o.png');
    pinLBUrl = ResolveURL('/images/pins/pin_b.png');

}





function ShowPins(_data)
{

    var currentPos = null;
    var bounds = new google.maps.LatLngBounds();
    var currentPin = null;
    var currentObj = null;
    var currentContent = null;

    this.lastList = _data;
    //pinList = new Array();

    clearOverlays();

    var currentIcon = new google.maps.MarkerImage(
    // the url of the marker
      pinUrl,
    // This marker is 20 pixels wide by 32 pixels tall. 
      new google.maps.Size(15, 48),
    // The origin for this image is 0,0. 
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32. 
      new google.maps.Point(1, 47));

    for (var i = 0; i < lastList.length; i++)
    {
        currentObj = lastList[i];
        currentPos = new google.maps.LatLng(currentObj.la, currentObj.lo);
        currentContent = "<p>" + currentObj.na + "</p><p>" + currentObj.ad + "</p>";

        currentPin = new google.maps.Marker({
            position: currentPos,
            html: currentContent,
            icon: currentIcon,
            map: mapObj,
            title: currentObj.na,
            index: i
        });

        pinList.push(currentPin);

        google.maps.event.addListener(currentPin, 'click', function()
        {
            SelectPin(this.index, true);
        });

        bounds.extend(currentPos);
    }

    //Fit these bounds to the map
    mapObj.fitBounds(bounds);
}



function ShowLocationPin(_lat, _lon, _locationS)
{

    var currentPos = null;
    //currentPin = null;
    var currentContent = null;

    if (locationPin != null)
    {
        locationPin.setMap(null);
        locationPin = null;
    }

    var currentIcon = new google.maps.MarkerImage(
    // the url of the marker
      pinLBUrl,
    // This marker is 20 pixels wide by 32 pixels tall. 
      new google.maps.Size(15, 48),
    // The origin for this image is 0,0. 
      new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at 0,32. 
      new google.maps.Point(1, 47));


    currentPos = new google.maps.LatLng(_lat, _lon);
    currentContent = "<p>Ihr Standort:</p><p>" + _locationS + "</p><p>Lat: " + _lat + "</p><p>Lon: " + _lon + "</p>";

    locationPin = new google.maps.Marker({
        position: currentPos,
        html: currentContent,
        icon: currentIcon,
        map: mapObj,
        title: "Ihr Standort",
        index: 0
    });

    mapObj.setCenter(currentPos);

    google.maps.event.addListener(locationPin, 'click', function()
    {
        infowindow.setContent(currentContent);
        infowindow.open(mapObj, locationPin);
    });
    
}


function ResetMap()
{
    clearOverlays();
    mapObj.setCenter(new google.maps.LatLng(47.5, 13.3));
}

function clearOverlays()
{

    if (infowindow != null)
    {
        infowindow.close();
    }
    if (pinList != null && pinList.length > 0)
    {
        for (var i = 0; i < pinList.length; i++) {
            pinList[i].setMap(null);
        }
    }

    //pinList = null;
    pinList = [];
}

function SelectPin(_index, _rfl)
{

    var pin = pinList[_index];
    var obj = lastList[_index];
    infowindow.setContent("<p>" + obj.na + "</p><p>" + obj.ad + "</p>");
    infowindow.open(mapObj, pin);
    if (_rfl)
    {
        view.SelectItem(_index);
    }
}


function PinDragEnd(_mouseEvent)
{
    ShowCurrentLocation();
}

function DoSearchForLocation(_address)
{
    //alert(_address);

    geocoderObj.geocode({ 'address': _address }, function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {
            mapObj.setCenter(results[0].geometry.location);
            currentPin.setPosition(results[0].geometry.location);
            ShowCurrentLocation();
        }
        else
        {
            alert("Adresse konnte nicht gefunden werden!\nÄndern Sie Ihre Eingaben und versuchen Sie es bitte erneut!");
        }
    });

}

function SetLocation(_lat, _lon)
{
    var pos = new google.maps.LatLng(_lat, _lon);
    map.setCenter(pos);
}

function ShowCurrentLocation()
{
    $("#lblLat").html(currentPin.position.lat());
    hfLat.val(currentPin.position.lat());
    $("#lblLon").html(currentPin.position.lng());
    hfLon.val(currentPin.position.lng());
}





s3c.lunchpin.views.Default = function () {
    var ListID = '#ulResultList';
    var resultListID = null;
    var resultDataTemplateID = null;
    var resultEmptyTemplateID = null;
    var ddlCatID = null;
    var ddlCountryID = null;
    var lastData = null;
    var progressBar = null;
    var geocoderObj = null;
    var STI = 0;
    var DTI = 0;

    /*PUBLIC METHODS*/
    this.Initialize = function (_id, _ddlCatID, _ddlCountryID) {
        progressBar = $("#" + _id + "_divProgress");
        resultListID = "#" + _id + "_divRLD";
        resultDataTemplateID = "#" + _id + "_divRLT";
        resultEmptyTemplateID = "#" + _id + "_divRLE";
        ddlCatID = "#" + _ddlCatID;
        ddlCountryID = "#" + _ddlCountryID;
        geocoderObj = new google.maps.Geocoder();
    }


    this.InitSBT = function () {
        $('#divSBT_1').attr('class', 'clSBT');
        $('#divSB_1').hide();

        $('#divSBT_0').attr('class', 'clSBTS');
        $('#divSB_0').show();
    }
    this.InitDBT = function () {
        $('#divDBT_1').attr('class', 'clDBT');
        $('#divDB_1').hide();

        $('#divDBT_0').attr('class', 'clDBTS');
        $('#divDB_0').show();
    }

    this.ToggleSBT = function (_index) {
        if (_index != STI) {
            $('#divSBT_' + STI).attr('class', 'clSBT');
            $('#divSB_' + STI).hide();

            $('#divSBT_' + _index).attr('class', 'clSBTS');
            $('#divSB_' + _index).show();
            STI = _index;
        }
    }

    this.ToggleDBT = function (_index) {
        if (_index != DTI) {
            $('#divDBT_' + DTI).attr('class', 'clDBT');
            $('#divDB_' + DTI).hide();

            $('#divDBT_' + _index).attr('class', 'clDBTS');
            $('#divDB_' + _index).show();

            DTI = _index;
        }
    }

    var lastIndex = -1;

    this.SelectItem = function (_index) {
        if (lastIndex != _index) {
            lastIndex = _index;
            UnselectAll();
            ShowSelected(_index);
            SelectPin(_index);
            LoadMenuData(_index);
        }
    }



    var UnselectAll = function () {
        var divID = "";
        for (var i = 0; i < lastData.length; i++) {
            divID = "#divRIBO_" + lastData[i].i;
            $(divID).attr("class", "clRIBO");
        }
    }

    var ShowSelected = function (_index) {
        var id = "#divRIBO_" + _index;
        $(id).attr("class", "clRIBOS");
    }

    var currentLocationSearchString = null;
    this.DoLBSearch = function () {

        var zipTerm = $("#tbxLBZip").val();
        var cityTerm = $("#tbxLBCity").val();
        var streetTerm = $("#tbxLBStreet").val();

        if (zipTerm != "" || cityTerm != "" || streetTerm != "") {
            ShowProgress();

            var countryID = $(ddlCountryID).val();
            var selectorID = ddlCountryID + " [value='" + countryID + "']"
            var countryName = $(selectorID).text();


            currentLocationSearchString = countryName + ", ";
            if (zipTerm != "") {
                currentLocationSearchString += zipTerm + ", ";
            }
            if (cityTerm != "") {
                currentLocationSearchString += cityTerm + ", ";
            }
            if (streetTerm != "") {
                currentLocationSearchString += streetTerm;
            }
            GeocodeAddress(currentLocationSearchString);
        }
    }

    function GeocodeAddress(_address) {
        //alert(_address);

        geocoderObj.geocode({ 'address': _address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                OnAfterGeocode(1, results[0].geometry.location);
            }
            else {
                OnAfterGeocode(0, null);
            }
        });
    }

    function OnAfterGeocode(_status, _location) {
        if (_status == 1) {
            RequestSearchResultsLatLon(_location.lat(), _location.lng());
            //ShowLocationPin(_lat, _lon);
        }
        else {
            // no results found
            HideProgress();
            alert("Es konnte kein entsprechender Standort gefunden werden!<br />Ändern Sie bitte die Eingabe und versuchen Sie es noch einmal");
        }
    }

    var RequestSearchResultsLatLon = function (_lat, _lon) {

        // display the location on the map
        //var baseUrl = "/lunchpinwebapp/handlers/dataservice.ashx";
        var baseUrl = ResolveURL("/handlers/dataservice.ashx");
        var queryPattern = "?op=findaccounts&lat={0}&lon={1}&type=json";


        var queryString = queryPattern.
        replace("{0}", _lat).
        replace("{1}", _lon);

        var finalUrl = baseUrl + queryString;

        InitSearchResults();
        ShowLocationPin(_lat, _lon, currentLocationSearchString);

        $.ajax({
            type: "GET",
            url: finalUrl,
            data: "",
            dataType: "text",
            cache: false,
            error: RequestSearchResults_OnError,
            success: RequestSearchResults_OnSuccess
        });
    }


    this.DoFullSearch = function () {


        var searchTerm = $("#tbxSearchTerm").val();
        var cityTerm = $("#tbxCityTerm").val();
        var zipTerm = $("#tbxZipTerm").val();
        var catVal = $(ddlCatID).val();
        if (searchTerm != "") {
            ShowProgress();
            //alert(searchTerm);
            RequestSearchResultsFullText(searchTerm, cityTerm, zipTerm, catVal);
        }
    }

    var RequestSearchResultsFullText = function (_searchterm, _cityTerm, _zipTerm, _catID) {
        var encSearchTerm = _searchterm != "" ? $.URLEncode(_searchterm) : "";
        var encCityTerm = _cityTerm != "" ? $.URLEncode(_cityTerm) : "";
        var encZipTerm = _zipTerm != "" ? $.URLEncode(_zipTerm) : "";
        //var baseUrl = "/lunchpinwebapp/handlers/dataservice.ashx";
        var baseUrl = ResolveURL("/handlers/dataservice.ashx");
        var queryPattern = "?op=findaccounts_fts&st={0}&ci={1}&zc={2}&ti={3}&t=20&type=json";

        var queryString = queryPattern.
        replace("{0}", encSearchTerm).
        replace("{1}", encCityTerm).
        replace("{2}", encZipTerm).
        replace("{3}", _catID);

        var finalUrl = baseUrl + queryString;

        InitSearchResults();
        $.ajax({
            type: "GET",
            url: finalUrl,
            data: "",
            dataType: "text",
            cache: false,
            error: RequestSearchResults_OnError,
            success: RequestSearchResults_OnSuccess
        });
    }


    var RequestSearchResults_OnError = function (XMLHttpRequest, textStatus, errorThrown) {
        var s = textStatus;
        HideProgress();
        ShowWarning("ERROR!", textStatus);
    }

    var isSearchInit = false;
    var InitSearchResults = function () {
        if (!isSearchInit) {
            $("#sv_divStartupBox").hide();
            $("#sv_divSearchResultBox").show();
            InitMapping('sv_divMaps_Canvas');
            isSearchInit = true;
        }
    }

    var RequestSearchResults_OnSuccess = function (_data) {
        var ajaxData = JSON.parse(_data);
        if (ajaxData != null) {
            // cache the last received data
            lastData = ajaxData.da;

            //var data = ajaxData;
            var msg = ajaxData.st.sm;

            //InitSearchResults();

            switch (ajaxData.st.sc) {
                // SUCCESS                                       
                case 0:
                    if (lastData.length == 0) {
                        DisplayEmptyResults();
                    }
                    else {
                        DisplayResults(lastData);
                    }
                    break;
                case -1:
                    ShowWarning("Warning!", msg);
                    break;
                case -4:
                    //ShowWarningForUrl();
                    ShowWarning("Warning!", msg);
                    break;
                case -2:
                case -3:
                case -5:
                    //ShowWarningForCustomUrl();
                    ShowWarning("Warning!", msg);
                    break;
                case -6:
                    //ShowWarningForPasscode();
                    ShowWarning("Warning!", msg);
                    break;
                case -20:
                    //ShowWarningForUrl();
                    ShowWarning("Warning!", msg);
                    break;
                default:
                    ShowWarning("Warning!", msg);
                    //ShowStatus("Success! " + data.ResultMessage);
                    //DisplayResults(data);
                    break;
            }
        }
        HideProgress();
    }


    var DisplayEmptyResults = function () {
        try {
            var preview = $(resultListID);
            $(resultListID).html($(resultEmptyTemplateID).html());
            //$(resultEmptyTemplateID).bindTo(data.da, { root: 'data', fillTo: resultListID });
            preview.show();

            //ResetMap();
        }
        catch (_ex) {
            alert(_ex.message);
        }
    }

    var DisplayResults = function (data) {
        try {
            // render the result list
            var preview = $(resultListID);
            $(resultDataTemplateID).bindTo(data, { root: 'data', fillTo: resultListID });
            preview.show();

            // then render the pins
            ShowPins(data);
        }
        catch (_ex) {
            alert(_ex.message);
        }
    }

    var LoadMenuData = function (_i) {
        var item = lastList[_i];
        //alert('Loading menu data for id:[' + item.id + ']');
    }
    var DisplayMenu = function () {
        //alert('Displaying menues...');
    }

    var ShowWarning = function (_caption, _text) {
        var warningBox = $('#sv_divResultsWarning');
        var warningCaption = $('#sv_lblResultWarningCaption');
        var warningText = $('#sv_lblResultWarningText');

        warningCaption.html(_caption);
        warningText.html(_text);
        warningBox.show();
        DisplayEmptyResults();
    }

    var ShowProgress = function () {
        progressBar.show();
        //btnSave.attr("disabled", "true");
        //btnSave.hide();
    }

    var HideProgress = function () {
        progressBar.hide();
        //btnSave.show();
        // btnSave.removeAttr("disabled");
    }
};

(function ($) {
    $.fn.inputHints = function () {

        $(this).each(function (i) {

            if ($(this).val() == '') {
                $(this).val($(this).attr('title')).addClass('input_blur');
            };
        });


        $(this)

.focus(function () {
    if ($(this).val() == $(this).attr('title'))
        $(this).val('').removeClass('input_blur').addClass('input_focus');
    else
        $(this).select();
})

.blur(function () {
    if ($(this).val() == '')
        $(this).val($(this).attr('title')).removeClass('input_focus').addClass('input_blur');
});
        $('form').submit(function () {
            $('.input_blur').val('');
            return true;
        });
    };
})(jQuery);


var ASSET_IMG_UserToggleFav = '/images/icons/tb/fav{0}.png'
function ToggleFav(_aid) {
    //alert('AID:' + _aid);

    var url = "/services/datasvc.ashx?op=togglefav&aid=" + _aid;

    $('#img_user_toggle_fav').attr('src', '/images/spinner3.gif');
    var ajaxCall = $.ajax({
        type: "GET",
        url: url,
        cache: false,
        dataType: "json",
        success: OnToggleFavSuccess,
        error: OnToggleFavError
    });
}

function OnToggleFavSuccess(data) {
    var reqst = data.st.sc;
    var imgsrc = null;
    if (reqst == 0) {
        //$('#lblStatus').html(data.st.sm);
        if (data.da.favstate >= 0) {
            imgsrc = ASSET_IMG_UserToggleFav.replace('{0}', data.da.favstate);
        }
        else {
            imgsrc = ASSET_IMG_UserToggleFav.replace('{0}', 0);
        }
    }
    else {
        // error
        //$('#lblStatus').html(data.st.sm);
        imgsrc = ASSET_IMG_UserToggleFav.replace('{0}', 0);
    }

    $('#img_user_toggle_fav').attr('src', imgsrc);
}


function OnToggleFavError(xhr, ajaxOptions, thrownError) {
    //$('#lblStatus').html(xhr.statusText);
    $('#img_user_toggle_fav').attr('src', ASSET_IMG_UserToggleFav.replace('{0}', 0));
}
