/**
 * check to see if console exists. If not, create an empty object for it,
 * then create and empty logging function which does nothing. 
 * 
 * IMPORTANT NOTICE: put this before any other console.log calls
 */
!window.console && ( window.console = {
    log:function( ){ },
    debug:function( ){ },
    info:function( ){ },
    warn:function( ){ },
    error:function( ){ },
    assert:function( ){ },
    clear:function( ){ },
    dir:function( ){ },
    dirxml:function( ){ },
    trace:function( ){ },
    group:function( ){ },
    groupCollapsed:function( ){ },
    groupEnd:function( ){ },
    time:function(){ },
    timeEnd:function( ){ },
    profile:function( ){ },
    profileEnd:function( ){ },
    count:function( ){},
    exception:function( ){ },
    table:function( ){ }
});

/**
 * Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
(function() {
    var initializing = false, fnTest = /xyz/.test(function() {xyz;}) ? /\b_super\b/ : /.*/;
    this.Class = function() {};
    Class.extend = function(prop) {
        var _super = this.prototype;
        initializing = true;
        var prototype = new this();
        initializing = false;
        for (var name in prop) {
            prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn) {
                return function() {
                    var tmp = this._super;
                    this._super = _super[name];
                    var ret = fn.apply(this, arguments);
                    this._super = tmp;
                    return ret;
                };
            })(name, prop[name]) : prop[name];
        }
        function Class() {
            if (!initializing && this.init) this.init.apply(this, arguments);
        }
        Class.prototype = prototype;
        Class.constructor = Class;
        Class.extend = arguments.callee;
        return Class;
    };
})();

/** 
 * Flash Search Controller
 */
var FlashSearchController = (function() {
    var defaults = {
        searchId: '#flash-search',
        formId: "#frm-flash-search",
        inputSearch: "#frm-search",
        prevButton: "#link-page-previous",
        nextButton: "#link-page-next",
        flashFilm: "#flash-pdf-reader",
        resultId: "#flash-search-result"
    };
    var currentResult = 0, 
        flashSearch, 
        resultCount, 
        searchForm, 
        inputSearch, 
        nextButton, 
        prevButton, 
        flashObj;
    var setResultText = function(){
        if ( resultCount > 0) {
            resultText.text("Ergebnis " + ( currentResult + 1 ) + " von " + resultCount );
        } else {
            resultText.text("Ihre Suche ergab leider keine Treffer.");
        }
    };
    var gotoNextResult = function() {
        if( resultCount > 0 ){
            flashObj.gotoNextResult();
            currentResult = flashObj.getCurrentResult();
            setResultText();
        }
    };
    var gotoPreviousResult = function() {
        if( resultCount > 0 ){
            flashObj.gotoPreviousResult();
            currentResult = flashObj.getCurrentResult();
            setResultText();
        }
    };
    return (function(settings) {
        var self = this;
        var options = $.extend(true, defaults, settings);
        
        this.start = function(){
            flashObj = $(options.flashFilm)[0];
            
        	/*
        	resultCount = flashObj.getTotalResults();
            if( resultCount > 0 ){
                setResultText();
            } 
            */
            
        	// We use this code because the code above doesnt't work on IE when query uses quotes (")
        	inputSearch = $(options.inputSearch, self.flashSearch);
            var query = inputSearch.val();
            if (query !== "" && query !== "Angebot suchen") {
                resultCount = flashObj.search(query);
                currentResult = 0;
                setResultText();
            } 

            flashSearch.css({
                display: "block"
            });            
        }
        
        var init = function() {
            flashSearch = $(options.searchId);
            if( flashSearch !== undefined ){
	            searchForm = $(options.formId, self.flashSearch);
	            inputSearch = $(options.inputSearch, self.flashSearch);
	            nextButton = $(options.nextButton, self.flashSearch).click(gotoNextResult);
	            prevButton = $(options.prevButton, self.flashSearch).click(gotoPreviousResult);
	            resultText = $(options.resultId, self.flashSearch).text('');
	            
	            searchForm.submit(function() {
	                var query = inputSearch.val();
	                if (query !== "") {
	                    resultCount = flashObj.search(query);
	                    currentResult = 0;
	                    setResultText();
	                } 
	                return false;
	            });
            }
        };
        init();
    })
})();

/** 
 * Ajax Filter Controller
 */
var AjaxFilter = Class.extend({
    usedForms: [],
    activeForm: false,
    distance:false,
    defaults: {
        activeClassName: 'active',
        resultListObj: '#offer-result-list',
        defaultActiveObj: '#frm-filter-reset',
        categoryFormId: '#frm-category-filter',
        dealerFormId: '#frm-dealer-filter',
        dealerId: false
    },
    init: function( settings ) {
        var self = this;
        this.options = $.extend( true, this.defaults, settings );
        
        // bind some events
        $( '#link-reset-filter' ).click( function( event ) {
        	$( self.options.categoryFormId + ', ' + self.options.dealerFormId ).removeClass( 'active' ).find( ':checkbox' ).attr( 'checked', false );
        	$( self.options.defaultActiveObj ).addClass( 'active' );
        } );
        
        $( self.options.categoryFormId ).find( ':checkbox' ).click( function( event ) {
        	$( self.options.categoryFormId ).addClass( 'active' );
        	$( self.options.dealerFormId ).removeClass( 'active' ).find( ':checkbox' ).attr( 'checked', false );
        	$( self.options.defaultActiveObj ).removeClass( 'active' );
        } );
        
        $( self.options.dealerFormId ).find( ':checkbox' ).click( function( event ) {
        	$( self.options.dealerFormId ).addClass( 'active' );
        	$( self.options.categoryFormId ).removeClass( 'active' ).find( ':checkbox' ).attr( 'checked', false );
        	$( self.options.defaultActiveObj ).removeClass( 'active' );
        } );
        
        // filter elements
        this.element = $( this.options.obj );
        $.each( this.element, function( index, elm ){
            // add this form to forms used by this application
        	self.usedForms.push( elm );
            
            // reset form
            self.clearForm( this );
            
            // auto submit on change
            $( ':radio, :checkbox, #link-reset-filter', $( elm ) ).click( function( ) {
                $( this ).closest( 'form' ).submit( );
            });
            
            // change handler for distance select
            $( '#frm-distance-select' ).change( function( ) {
                self.distance = $( 'option:selected', this ).val( );
                $('.sitenavi-coll form.active').submit( );
            } );
            
            // submit handler
            $( elm ).submit(function() {
                var dataStr = $( this ).serialize();
                if ( self.distance ) dataStr += ( dataStr.length ? '&' : '' ) + 'umkreis=' + self.distance
                $.ajax({
                    url: $( this ).attr("action"),
                    data: dataStr,
                    type: 'GET',
                    dataType: "json",
                    success: function( response ) {
                        self.buildList( response.results );
                        Page.gmc.buildMapMarkers(response.markers, response.map);
                    },
                    error: function( xhr, ajaxOptions, thrownError ) {
                        // shouldn't ever happen, at all!
                    	console.log( '[AJAX Error: "' + xhr.responseText + '"; options: ' + ajaxOptions +  ']: ' + thrownError );
                    }
                });
                return false;
            })
        });
    },
    buildList: function( ) { },
    clearForm: function( el ) {
        var newForm = $( el );
        $.each(this.usedForms, function(index, value) {
            if ( value !== el ) {
                $("input:checkbox:checked", value ).attr("checked", false);
                $( value ).removeClass('active');
            }
        });
        if ($('input:checkbox,input:radio', newForm ).length > 0 && $('input:checkbox:checked,input:radio:checked', newForm).length === 0) {
            newForm.removeClass('active');
            $( this.options.defaultActiveObj ).addClass('active');
        } else {
            newForm.addClass('active');
        }
    }
});

/** 
 * Offer List Controller
 */
var OfferList = AjaxFilter.extend({
    init: function( settings ){
        this._super( settings );
        var self = this;
        
        // reset
        $( 'input[class*="frm-filter-checkbox"]' ).attr( 'checked', false );
        
        // select fields
        var autoCat = filterHashCmd( 'cat' );
        if ( autoCat !== false ) {
        	for( var s in autoCat ) {
        		$( 'input[id^="category-"][value="' + autoCat[ s ] + '"]' ).attr( 'checked', true );
        	}
        	$( this.options.categoryFormId ).addClass( 'active' ).submit( );
        	$( this.options.defaultActiveObj ).removeClass( 'active' );
        }
        else if ( this.options.dealerId !== false ) {
            $( 'input:checkbox', $( this.options.dealerFormId ) ).each( function( ) {
            	var $this = $(this);
                if ($this.val( ) == self.options.dealerId ) {
                	$this.attr( "checked", true );
                }
            });
            $( this.options.dealerFormId ).addClass( 'active' ).submit( );
            $( this.options.defaultActiveObj ).removeClass( 'active' );
        } 
        else {
            $( this.options.defaultActiveObj ).submit( );
        }
    },
    buildList: function(dataObj) {
        var html = '';
        $.each( dataObj, function( index, listItem ) {
            html += '<div class="offer offer-' + listItem.id + '">';
            html += '<div class="offer-icon"></div>';
            html += '<div class="offer-img">';
            html += '<a href="' + listItem.broshure + '" class="thickbox">';
            html += '<img src="' + listItem.img + '" alt="' + listItem.name + '" />';
            html += '</a>';
            html += '</div>';
            html += '<div class="offer-content">';
            html += '<a href="' + listItem.broshure + '" class="link-arrow thickbox">' + listItem.name + "</a><br />";
            html += listItem.validUntil + '</div>';
            html += '<div class="offer-number">';
            if ( !listItem.onlineDealer && listItem.id > 0 ) {
                html += '<div class="location-icon">';
                html += '<div class="location-icon-number">' + listItem.id + '</div>';
                html += '</div>';
            } 
            else {
                html += '<div class="location-icon"><div class="location-icon-web" style="bottom: -2px"></div></div>';
            }
            html += '</div>';
            html += '</div>';
        } );
        
        $( this.options.resultListObj ).fadeOut( 400, function( ) {
        	try {
        		var self = $( this );
	            self.html( html ).fadeIn( 400 );
	            makeItemHover( );
        	} 
        	catch( e ) { }
        } );
            
    }
});

/** 
 * Dealer List Controller
 */
var DealerList = AjaxFilter.extend({
    init: function( settings ){
        this._super( settings );
        $(this.options.defaultActiveObj).submit();
    },
    buildList: function(dataObj) {
        var html = '';
        $.each(dataObj, function(index, listItem) {
            html += '<div class="dealer' + (listItem.offer !== undefined ? ' hasOffer' : '') + '"><div class="dealer-block"><div class="dealer-logo">';
            if (listItem.offer === undefined) {
                html += '<img src="' + listItem.img + '" alt="' + listItem.name + '" /></div><div class="dealer-offer">Keine Angebote</div></div>';
            } else {
                html += '<a href="' + listItem.offer + '"><img src="' + listItem.img + '" alt="' + listItem.name + '" /></a></div><div class="dealer-offer"><a href="' + listItem.offer + '" class="link-arrow">Angebote</a></div></div>';
            }
            if (listItem.homepage !== undefined) {
                html += '<a target="_blank" class="link-arrow" href="' + listItem.homepage + '">Homepage</a>';
            }
            html += '</div>';
        });
        
        $( this.options.resultListObj ).fadeOut(400, function(event) {
            $(this).html(html).fadeIn(400);
        })
    }
});

/** 
 * Location Controller
 */
var GoogleMapController = (function() {
    var markers = [];
    var map = { };
    var defaults = {
        lng: 10.305176,
        lat: 50.481745,
        zoom: 10,
        canvas: "#map-canvas",
        list: "#map-locations",
        marker_icon: "/ea/etc/designs/einkaufaktuell/common/img/icon_google_map_marker.png",
        markers: []
    };
    var buildLocationListItem = function(data) {
        var MORE_SHOPS_MARKUP = '<div class="more-shops">' + 
        		'<a class="thickbox link-arrow" href="##LINK##">weitere Standorte</a>' + 
        		'</div>';
    	
        // make markup
        var htmlExtra = '';
        var html = '<div class="location location-' + data.id +  ' clearfix" title="' + data.name + '">';
        html += '<div class="location-logo">';
        if( typeof data.broshure != 'undefined' ) {
            html += '<a href="' + data.broshure + '" class="thickbox"><img src="' + data.img + '" width="38" height="38" alt="Logo ' + data.name + '" /></a>';
        } 
        else {
            html += '<img src="' + data.img + '" width="38" height="38" alt="Logo ' + data.name + '" />';
        }
        html += '</div>';
        html += '<div class="location-adress">';
        if ( !data.onlineDealer ) {
            if ( typeof data.broshure != 'undefined' ){
                html += '<h3>';
                html += '<a href="' + data.broshure + '" class="thickbox">' + data.name + '</a>'
                html += '</h3>';
                
                if ( typeof data.moreDealer != 'undefined' && data.moreDealer ) {
                	htmlExtra = MORE_SHOPS_MARKUP.replace(/\#\#LINK\#\#/g, data.broshure );
                }
            } 
            else {
                html += '<h3>' + data.name + '</h3>';
            }
            html += data.address + '<br />';
            html += data.opening;
            if ( typeof htmlExtra != 'undefined' ) {
            	html += htmlExtra;
            }
            html += '</div>';
            html += '<div class="location-icon">';
            html += '<div class="location-icon-number">' + data.id + '</div>';
            html += '</div>';
        } 
        else {
            html += "<h3>" + data.name + '</h3>';
            if (typeof data.link != 'undefined' && data.link.length > 0 ) {
                var linkName = ( data.link != 'http://clkde.tradedoubler.com/click?p=167843&a=1956350&g=19652522' ) ? data.link.substring( data.link.indexOf( '//' ) + 2, data.link.length ) : 'www.berge-meer.de';
                html += '<a href="' + data.link + '" target="_blank">' + linkName + "</a>";
                
                if ( typeof data.moreDealer != 'undefined' && data.moreDealer ) {
                	html += MORE_SHOPS_MARKUP.replace(/\#\#LINK\#\#/g, data.link );
                }
            }
            html += '</div>';
            html += '<div class="location-icon">';
            html += '<div class="location-icon-web"></div>';
            html += '</div>';
        }
        
        // more shops;
        html += '</div>';
        return html
    };
    return (function(settings) {
        var self = this;
        var options = $.extend(true, defaults, settings);
        this.buildMapMarkers = function(markerList, usermap) {
            var locationHTML = "";
            var _latLngBounds = new google.maps.LatLngBounds();
            var hasRegularDealers = false;
            
            if (markers.length > 0) {
                map.clearOverlays();
            }
            $.each(markerList, function(index, marker) {
                if( !marker.onlineDealer ){
                    hasRegularDealers = true;
                }
                if (marker.lat !== undefined && marker.lng !== undefined && marker.lat.length > 0 && marker.lng.length > 0) {
                    var currentLatLng = new GLatLng(marker.lat, marker.lng);
                    _latLngBounds.extend(currentLatLng);
                    var icon = new GIcon();
                    icon.image = options.marker_icon;
                    icon.iconSize = new GSize(17, 28);
                    icon.iconAnchor = new GPoint(16, 16);
                    icon.infoWindowAnchor = new GPoint(25, 7);
                    var opts = {
                        icon: icon,
                        clickable: true,
                        labelText: new String(index + 1),
                        labelOffset: new GSize(-16, -13)
                    };
                    var gmarker = new LabeledMarker(currentLatLng, opts);
                    map.addOverlay(gmarker);
                    markers.push(gmarker);
                }
                locationHTML += buildLocationListItem(marker);
            });
            if( !hasRegularDealers ){
                $('#map-canvas').css('display','none');
                $('#map-notice').css('display','block');
            } else {
                $('#map-canvas').css('display','block');
                $('#map-notice').css('display','none');
            }
            if (!_latLngBounds.isEmpty()) {
                var zoomLevel = (map.getBoundsZoomLevel(_latLngBounds) < 15) ? map.getBoundsZoomLevel(_latLngBounds) : 15;
                map.addControl(new GSmallMapControl());
                if ( usermap !== null ) {
                    //set fixed zoom level on angebote page 
                    var zoomLevel = ( !isNaN( usermap.zoom ) )? usermap.zoom:options.zoom;
                    map.setCenter(new GLatLng(usermap.lat, usermap.lng), zoomLevel );
                } else {
                    map.setCenter(_latLngBounds.getCenter(), zoomLevel);
                }
            } else {
                map.setCenter(new GLatLng(options.lat, options.lng), 5);
            }
            
            $( options.list ).html( locationHTML );
            
            // toggle scroll buttons here 
            toggleLocationScrollButtons( );
            
            // trigger page as soon as the object is available
            setTimeout( function( ) {
                if ( typeof Page == 'object' ) {
                    Page.addTrigger( );
                }
            }, 1000 );
        };
        
        var init = function( ) {
        	// inject scroll buttons
        	injectLocationScrollButtons( );
            
        	// make map
        	map = new GMap2($(options.canvas)[0],{size:new GSize(205,205)});
            
        	// add marker
        	if( options.markers.length > 0 ){
                self.buildMapMarkers(options.markers, null);
            }
        };
        
        init();
    })
})();

/** 
 * Page Controller.
 */
var PageController = (function() {
    var openDialog = function(hash){
        var $trigger = $(hash.t);
        var $modalWindow = $(hash.w);
        var $modalContainer = $('iframe', $modalWindow);
        var myUrl = $trigger.attr('href');
        var allowedParams = ['width','height','left','top'];
        var newCss = {};
        $modalContainer.html('').attr('src', myUrl);
        
        myUrl = (myUrl.lastIndexOf("#") > -1) ? myUrl.slice(0, myUrl.lastIndexOf("#")) : myUrl;
        var queryString = (myUrl.indexOf("?") > -1) ? myUrl.substr(myUrl.indexOf("?") + 1) : null;
        
        if (queryString != null && typeof queryString != 'undefined') {
            var queryVarsArray = queryString.split("&");
            for (var i = 0; i < queryVarsArray.length; i++) {
                var newKey = escape(unescape(queryVarsArray[i].split("=")[0]));
                var newValue = queryVarsArray[i].split("=")[1];
                if( $.inArray( newKey, allowedParams ) > -1 ){
                    newCss[ newKey ] = parseInt( newValue );
                }
                if ( newKey == 'jqmRefresh') {
                    hash.refreshAfterClose = newValue;
                } else {
                    hash.refreshAfterClose = false;
                }
            }
            if ( newCss.top === undefined ) {
                newCss.top = Math.floor( parseInt( $(window).height() - newCss.height ) / 2 );
            }
            if ( newCss.left === undefined ) {
                newCss.left = Math.floor( parseInt( $(window).width() / 2 ) - parseInt( newCss.width ) / 2 );
            }
            $modalWindow.css(newCss).show();
        } else {
            $modalWindow.jqmShow();
        }
    };
    var openIFrame = function(hash) {
        var $trigger = $(hash.t);
        var $modalWindow = $(hash.w);
        var $modalContainer = $('iframe', $modalWindow);
        var myUrl = $trigger.attr('href');
        var newWidth = 0, newHeight = 0;
        $modalContainer.html('').attr('src', myUrl);
        
        newWidth = $(window).width() - 40;
        newHeight = $(window).height() - 40;
        
        $modalWindow.css({
            width: newWidth,
            height: newHeight,
            marginTop: -(newHeight / 2),
            marginLeft: -(newWidth / 2)
        }).show();
    };
    var hideModal = function(hash) {
        var trigger = $(hash.t);
        var modal = $(hash.w);
        var modalContent = $('iframe', modal);
        var overlay = hash.o;
        modalContent.html('').attr('src','about:blank');
        modal.hide();
        if ( hash.refreshAfterClose === 'true' ) {
            window.location.href = document.location.href;
        }
        if (typeof overlay === 'object') {
            overlay.remove();
        }
    };
    var defaults = {
        offerlist:false,
        inlineLabel: {
            obj: "input[placeholder]"
        },
        jqmDialog: {
            obj: "#jqm-dialog",
            conf: {
                trigger: ".jqmDialog",
                target: "#jqm-dialog-content",
                overlay: false,
                onShow: openDialog,
                onHide: hideModal,
                overlayClass: "jqm-overlay"
            }
        },
        jqmBroshure: {
            obj: "#jqm-broshure",
            conf: {
                trigger: ".thickbox",
                target: "#jqm-broshure-content",
                onShow: openIFrame,
                onHide: hideModal,
                overlayClass: "jqm-overlay"
            }
        },
        googleMaps: {
            canvas: "#map-canvas",
            latLng: [53.56404, 9.97005],
            markers: []
        }
    };
    return (function(settings) {
        var self = this;
        var options = $.extend(true, defaults, settings);
        this.addTrigger = function() {
            $(options.jqmBroshure.obj).jqmAddTrigger(options.jqmBroshure.conf.trigger);
        };
        this.openModal = function(linkUrl) {
            var $modalContent = $("iframe", this.jqmBroshure);
            $modalContent.html("").attr("src", linkUrl);
            this.jqmBroshure.jqmShow();
        };
        this.init = function() {
            $("body").addClass("js");
            this.jqmDialog = $(options.jqmDialog.obj).jqm(options.jqmDialog.conf);
            this.jqmBroshure = $(options.jqmBroshure.obj).jqm(options.jqmBroshure.conf);
            $(options.inlineLabel.obj).inlinelabel();
            if ($(options.googleMaps.canvas).length) {
            	this.gmc = new GoogleMapController(options.googleMaps);
            }
            if( options.offerlist ) {
                this.ajaxsearch = new OfferList( options.offerlist );   
            } 
            else if( options.dealerlist ) {
                this.ajaxsearch = new DealerList( options.dealerlist );
            } 
            else {
                $( '#frm-distance-select' ).change( function( ) {
                    $( this ).closest( 'form' ).submit( );
                } );
            }
            
            //Add here the input field id
			var searchFieldPath = $("#frm-search");
			
			searchFieldPath.autocomplete(exoProxyUrl, exoSuggestParams).focus();
			searchFieldPath.result(exoSuggRedirect);
            // make hover effect
            makeItemHover( );
        };
        this.init();
    })
})();

/** 
 * jQuery Do
 */
(function($) {
    $.extend({
        inlinelabel: new function() {
            var defaults = {
                focusClassName: "focused"
            };
            var usedForms = [];
            var labeledInputs = [];
            var alterForm = function(obj) {
                var parentForm = $(obj).closest("form");
                if ($.inArray(parentForm[0], usedForms) == -1) {
                    parentForm.submit(function() {
                        $.each(labeledInputs, function(index, obj) {
                            if (obj.attr("value") == obj.attr("placeholder")) {
                                obj.attr("value", "");
                            }
                        })
                    });
                    usedForms.push(parentForm[0]);
                }
            };
            var placeholderTest = function(){
                return 'placeholder' in document.createElement('input');
            }
            this.construct = function(settings) {
                var options = $.extend(true, defaults, settings);
                return this.each(function() {
                    var self = $(this);
                    if( !placeholderTest() ){
                        alterForm(this);
                        if (self.val() === "") {
                            self.val(self.attr("placeholder"));
                        }
                        self.focus(function() {
                            if (self.val() === self.attr("placeholder")) {
                                self.val("").addClass(options.focusClassName);
                            }
                        });
                        self.blur(function() {
                            if (self.val() === "") {
                                self.val(self.attr("placeholder")).removeClass(options.focusClassName);
                            }
                        });
                        labeledInputs.push(self);
                    }
                })
            }
        }
    });
    $.fn.extend({
        inlinelabel: $.inlinelabel.construct
    })
})(jQuery);

/** 
 * Open dialog window.
 */
function openDialog( url ) {
    try { 
    	Page.openModal( url );
    }
    catch( e ) { }
};

/** 
 * Link banner.
 */
function openBannerUrl( url, target ) {
	try { 
		var windowName = ( arguments.length > 2 && arguments[ 2 ] ) ? arguments[ 2 ] : 'bannerWindow';
		var params = ( arguments.length > 3 ) ? arguments[ 3 ] : '';
		if( typeof target == 'undefined' || target == '_self' ){
			window.location.href= url;
		} 
		else {
			window.open( url, windowName, params, target );
		}
		
		var s = s_gi( s_account );
	    s.t( );
	}
    catch( e ) { }
};

/** 
 * Filter hash commands.
 */
function filterHashCmd( cmdRequired ) {
	if ( !cmdRequired ) return false;	// cmd required
	
	// get hash key
	var hash = unescape(window.location);
	if (hash.indexOf("#") == -1) return false;
		
	hash = hash.slice(hash.indexOf("#"));
	
	if ( hash.charAt( 0 ) == '#' ) hash = hash.substr( 1 );
	if ( !hash ) return false;
	
	// get seperator
	var spt = ( arguments.length > 1 ) ? arguments[ 1 ] : '+';
	if ( spt == '=' ) return false;	// "is equal" character is reserved for command from parameter seperation
	
	// get command from hash string
	var cmdHash = hash.split( '=' );
	if ( cmdHash.length < 2 || cmdHash[ 0 ].toLowerCase( ) != cmdRequired.toLowerCase( ) ) return false;	// unknown command
	
	// seperate parameters
	var paramsHash = cmdHash[ 1 ].split( spt );
	return ( paramsHash.length ) ? paramsHash : false;
}

/** 
 * Make item hover effect (offer and location).
 */
function makeItemHover( ) {
	try {
		$( '#offer-result-list' ).children('div[class*="offer-"]').each( function( idx, itm ) {
	    	var ofr = $( itm );
	    	var id = 0;
	    	var title = ofr.attr( 'title' );
	    	var cls = ofr.attr( 'class' ).split( ' ' );
	    	for( var s in cls ) {
	    		cls[ s ] = $.trim( cls[ s ] );
	    		if ( cls[ s ].substr( 0, 6 ) == 'offer-' ) {
	    			id = parseInt( cls[ s ].substr( 6 ) );
	    			break;
	    		}
	    	}
	    	
	    	if ( id ) {
	    		var loc = $( 'div[class*="location-' + id +  ' "]' );
	    		var mouseenter = function( evnt ) {
	    			ofr.addClass( 'hover' );
	    			loc.addClass( 'hover' );
	    		};
	    		var mouseleave = function( evnt ) {
	    			ofr.removeClass( 'hover' );
	    			loc.removeClass( 'hover' );
	    		}
	    		
	    		loc.mouseenter( mouseenter ).mouseleave( mouseleave );
	    		ofr.mouseenter( mouseenter ).mouseleave( mouseleave );
	    	}
	    } );
	}
	catch( e ) { }
}

/** 
 * Inject scroll buttons into location list.
 */
var __DEF_LOCSCROLL_SPEED = 500;
var __locScrollCurElmnt = 0;
var __locScrollMaxElmnt = false;
function __locScrollDoScroll( dir, speed ) {
	try {
		var maploc = $( '#map-locations' );
		var elmnts = maploc.children( 'div[class*="location"]' );
		var tih = 0;
		var sc = 0;
		
		// assume maximum scrolling position is the number of
		// location elements, if no numeric value has been set, yet.
		if ( __locScrollMaxElmnt === false ) __locScrollMaxElmnt = elmnts.length - 1;
		
		// set new elements
		__locScrollCurElmnt += dir;
		if ( __locScrollCurElmnt < 0 ) __locScrollCurElmnt = 0;
		if ( __locScrollCurElmnt > __locScrollMaxElmnt ) __locScrollCurElmnt = __locScrollMaxElmnt;
		
		// get scroll position
		elmnts.each( function( idx, itm ) {
			var oh = $( itm ).outerHeight( );
			tih += oh;
			if ( idx < __locScrollCurElmnt ) {
				sc += oh;
			}
		} );
		
		// check if maximum scrolling position has been reached, and
		// adjust maximum scrolling position
		tih -= maploc.height( );
		if ( sc > tih ) {
			__locScrollMaxElmnt = __locScrollCurElmnt;
		}
		
		// scroll to position
		if ( speed ) {
			maploc.animate( {
				scrollTop: sc
			}, {
				duration: speed
			} );
		}
		else {
			maploc.scrollTop( sc );
		}
	}
	catch( e ) { }
}
function injectLocationScrollButtons( ) {
	try {
		// do scrolling in dialogues, only
		if ( $( 'body#flashlayer' ).length != 1 ) return;
		
		// make and inject buttons
		var maploc = $( '#map-locations' );
		var scrollUp = $('<div id="scroll-up" class="locations-scroll locations-scroll-up">' + 
							'<a href="#">&nbsp;</a>' + 
			 			'</div>');
		var scrollDown = $( '<div id="scroll-down" class="locations-scroll locations-scroll-down">' + 
							'<a href="#">&nbsp;</a>' + 
						'</div>' );
		maploc.before( scrollUp );
		maploc.after( scrollDown );
		
		// initially hide both scroll buttons
		scrollUp.hide( );
		scrollDown.hide( );
		
		// bind events to scroll buttons
		scrollUp.children( 'a' ).click( function( event ) {
			event.preventDefault( );
			__locScrollDoScroll( -1, __DEF_LOCSCROLL_SPEED );
		} );
		
		scrollDown.children( 'a' ).click( function( event ) {
			event.preventDefault( );
			__locScrollDoScroll( 1, __DEF_LOCSCROLL_SPEED );
		} );
	}
	catch( e ) { }
}

/** 
 * Inject scroll buttons into location list.
 */
var __ie6RepeatTimer = 0;
function toggleLocationScrollButtons( ) {
	try {
		// do scrolling in dialogues, only
		if ( $( 'body#flashlayer' ).length != 1 ) return;
		
		// get available height
		var maxHeight = $( 'body' ).height( ) - ( $( '#head' ).height( ) + $( '#footer' ).height( ) );
		var canvas = $( '#map-canvas' );
		var notice = $( '#map-notice' );
		var distance = $( '#map-distance' );
		var locations = $( '#map-locations' );
		
		if ( __ie6RepeatTimer ) {	// ie6 fix
			clearTimeout( __ie6RepeatTimer );
			__ie6RepeatTimer = 0;
		}
		
		if ( !locations.height( ) ) {
			__ie6RepeatTimer = setTimeout( 'toggleLocationScrollButtons( )', 250 );
		}
		
		if ( canvas.is( ':visible' ) ) maxHeight -= canvas.outerHeight( );
		if ( notice.is( ':visible' ) ) maxHeight -= notice.outerHeight( );
		if ( distance.is( ':visible' ) ) maxHeight -= distance.outerHeight( );

		if ( locations.height( ) >  maxHeight ) {
			var scrollUp = $( '#scroll-up' );
			var scrollDown = $( '#scroll-down' );
			var h = maxHeight - ( scrollUp.outerHeight( ) + scrollDown.outerHeight( ) );
			
			// set height
			locations.css( {
				overflow: 'hidden',
				height: String( h ) + 'px'
			} );
			
			// show scroll buttons
			scrollUp.show( );
			scrollDown.show( );
		}
	}
	catch( e ) { }
}


