/*MooTools, My Object Oriented Javascript Tools. Copyright (c) 2006-2007 Valerio Proietti, <http://mad4milk.net>, MIT Style License.||Clientcide Copyright (c) 2006-2008, http://www.clientcide.com/wiki/cnet-libraries#license*/

var Clientcide = {
    version: '2.1.0',
    setAssetLocation: function (baseHref) {
        var clean = function (str) {
            return str.replace(/\/\//g, '/')
        };
        if (window.StickyWin && StickyWin.UI) {
            StickyWin.UI.implement({
                options: {
                    baseHref: clean(baseHref + '/stickyWinHTML/')
                }
            });
            if (StickyWin.Alert) {
                StickyWin.Alert.implement({
                    options: {
                        baseHref: baseHref + "/simple.error.popup"
                    }
                })
            }
            if (StickyWin.UI.Pointy) {
                StickyWin.UI.Pointy.implement({
                    options: {
                        baseHref: clean(baseHref + '/PointyTip/')
                    }
                })
            }
        }
        if (window.TagMaker) {
            TagMaker.implement({
                options: {
                    baseHref: clean(baseHref + '/tips/')
                }
            })
        }
        if (window.ProductPicker) {
            ProductPicker.implement({
                options: {
                    baseHref: clean(baseHref + '/Picker')
                }
            })
        }
        if (window.Autocompleter) {
            Autocompleter.Base.implement({
                options: {
                    baseHref: clean(baseHref + '/autocompleter/')
                }
            })
        }
        if (window.Lightbox) {
            Lightbox.implement({
                options: {
                    assetBaseUrl: clean(baseHref + '/slimbox/')
                }
            })
        }
        if (window.Waiter) {
            Waiter.implement({
                options: {
                    baseHref: clean(baseHref + '/waiter/')
                }
            })
        }
    },
    preLoadCss: function () {
        if (window.StickyWin && StickyWin.ui) StickyWin.ui();
        if (window.StickyWin && StickyWin.pointy) StickyWin.pointy();
        Clientcide.preloaded = true;
        return true
    },
    preloaded: false
};
(function () {
    if (!window.addEvent) return;
    var preload = function () {
        if (window.dbug) dbug.log('preloading clientcide css');
        if (!Clientcide.preloaded) Clientcide.preLoadCss()
    };
    window.addEvent('domready', preload);
    window.addEvent('load', preload)
})();
setCNETAssetBaseHref = Clientcide.setAssetLocation;
var dbug = {
    logged: [],
    timers: {},
    firebug: false,
    enabled: false,
    log: function () {
        dbug.logged.push(arguments)
    },
    nolog: function (msg) {
        dbug.logged.push(arguments)
    },
    time: function (name) {
        dbug.timers[name] = new Date().getTime()
    },
    timeEnd: function (name) {
        if (dbug.timers[name]) {
            var end = new Date().getTime() - dbug.timers[name];
            dbug.timers[name] = false;
            dbug.log('%s: %s', name, end)
        } else dbug.log('no such timer: %s', name)
    },
    enable: function (silent) {
        var con = window.firebug ? firebug.d.console.cmd : window.console;
        if (( !! window.console && !! window.console.warn) || window.firebug) {
            try {
                dbug.enabled = true;
                dbug.log = function () {
                    (con.debug || con.log).apply(con, arguments)
                };
                dbug.time = function () {
                    con.time.apply(con, arguments)
                };
                dbug.timeEnd = function () {
                    con.timeEnd.apply(con, arguments)
                };
                if (!silent) dbug.log('enabling dbug');
                for (var i = 0; i < dbug.logged.length; i++) {
                    dbug.log.apply(con, dbug.logged[i])
                }
                dbug.logged = []
            } catch (e) {
                dbug.enable.delay(400)
            }
        }
    },
    disable: function () {
        if (dbug.firebug) dbug.enabled = false;
        dbug.log = dbug.nolog;
        dbug.time = function () {};
        dbug.timeEnd = function () {}
    },
    cookie: function (set) {
        var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
        var debugCookie = value ? unescape(value[1]) : false;
        if ((!$defined(set) && debugCookie != 'true') || ($defined(set) && set)) {
            dbug.enable();
            dbug.log('setting debugging cookie');
            var date = new Date();
            date.setTime(date.getTime() + (24 * 60 * 60 * 1000));
            document.cookie = 'jsdebug=true;expires=' + date.toGMTString() + ';path=/;'
        } else dbug.disableCookie()
    },
    disableCookie: function () {
        dbug.log('disabling debugging cookie');
        document.cookie = 'jsdebug=false;path=/;'
    }
};
(function () {
    var fb = !! window.console || !! window.firebug;
    var con = window.firebug ? window.firebug.d.console.cmd : window.console;
    var debugMethods = ['debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml'];
    var otherMethods = ['trace', 'group', 'groupEnd', 'profile', 'profileEnd', 'count'];

    function set(methodList, defaultFunction) {
        for (var i = 0; i < methodList.length; i++) {
            dbug[methodList[i]] = (fb && con[methodList[i]]) ? con[methodList[i]] : defaultFunction
        }
    };
    set(debugMethods, dbug.log);
    set(otherMethods, function () {})
})();
if (( !! window.console && !! window.console.warn) || window.firebug) {
    dbug.firebug = true;
    var value = document.cookie.match('(?:^|;)\\s*jsdebug=([^;]*)');
    var debugCookie = value ? unescape(value[1]) : false;
    if (window.location.href.indexOf("jsdebug=true") > 0 || debugCookie == 'true') dbug.enable();
    if (debugCookie == 'true') dbug.log('debugging cookie enabled');
    if (window.location.href.indexOf("jsdebugCookie=true") > 0) {
        dbug.cookie();
        if (!dbug.enabled) dbug.enable()
    }
    if (window.location.href.indexOf("jsdebugCookie=false") > 0) dbug.disableCookie()
}
var Autocompleter = {};
var OverlayFix = IframeShim;
Autocompleter.Base = new Class({
    Implements: [Options, Events],
    options: {
        minLength: 1,
        markQuery: true,
        width: 'inherit',
        maxChoices: 10,
        className: 'autocompleter-choices',
        zIndex: 42,
        delay: 400,
        observerOptions: {},
        fxOptions: {},
        autoSubmit: false,
        overflow: false,
        overflowMargin: 25,
        selectFirst: false,
        filter: null,
        filterCase: false,
        filterSubset: false,
        forceSelect: false,
        selectMode: true,
        choicesMatch: null,
        multiple: false,
        separator: ', ',
        autoTrim: true,
        allowDupes: false,
        cache: true,
        relative: false,
		urlBase : "/solr-news/select/",
		searchFormInput :'search-text',
		searchPageUrl:'/news/search_results.html'
		
    },
    initialize: function (element, options) {
        this.element = document.id(element);
        this.setOptions(options);
        this.options.separatorSplit = new RegExp("\s*[" + this.options.separator.trim() + "]\s*/");
        this.build();
        this.observer = new Observer(this.element, this.prefetch.bind(this), $merge({
            'delay': this.options.delay
        }, this.options.observerOptions));
        this.queryValue = null;
        if (this.options.filter) this.filter = this.options.filter.bind(this);
        var mode = this.options.selectMode;
        this.typeAhead = (mode == 'type-ahead');
        this.selectMode = (mode === true) ? 'selection' : mode;
        this.cached = []
    },
    build: function () {
        if (document.id(this.options.customChoices)) {
            this.choices = this.options.customChoices
        } else {
            this.choices = new Element('ul', {
                'class': this.options.className,
                'styles': {
                    'zIndex': this.options.zIndex
                }
            }).inject(document.body);
            this.relative = false;
            if (this.options.relative || this.element.getOffsetParent() != document.body) {
                this.choices.inject(this.element, 'after');
                this.relative = this.element.getOffsetParent()
            }
            this.fix = new OverlayFix(this.choices)
        }
        if (!this.options.separator.test(this.options.separatorSplit)) {
            this.options.separatorSplit = this.options.separator
        }
        this.fx = (!this.options.fxOptions) ? null : new Fx.Tween(this.choices, $merge({
            'property': 'opacity',
            'link': 'cancel',
            'duration': 200
        }, this.options.fxOptions)).addEvent('onStart', Chain.prototype.clearChain).set(0);
        this.element.setProperty('autocomplete', 'off').addEvent((Browser.Engine.trident || Browser.Engine.webkit) ? 'keydown' : 'keypress', this.onCommand.bind(this)).addEvent('click', this.onCommand.bind(this, [false])).addEvent('focus', this.toggleFocus.create({
            bind: this,
            arguments: true,
            delay: 100
        }));
        document.addEvent('click', function (e) {
            if (e.target != this.choices) this.toggleFocus(false)
        }.bind(this))
    },
    destroy: function () {
        if (this.fix) this.fix.dispose();
        this.choices = this.selected = this.choices.destroy()
    },
    toggleFocus: function (state) {
        this.focussed = state;
        if (!state) this.hideChoices(true);
        this.fireEvent((state) ? 'onFocus' : 'onBlur', [this.element])
    },
    onCommand: function (e) {
        if (!e && this.focussed) return this.prefetch();
        if (e && e.key && !e.shift) {
            switch (e.key) {
            case 'enter':
                if (this.element.value != this.opted) return true;
                if (this.selected && this.visible) {
                    this.choiceSelect(this.selected);
                    return !!(this.options.autoSubmit)
                }
                break;
            case 'up':
            case 'down':
                if (!this.prefetch() && this.queryValue !== null) {
                    var up = (e.key == 'up');
                    this.choiceOver((this.selected || this.choices)[(this.selected) ? ((up) ? 'getPrevious' : 'getNext') : ((up) ? 'getLast' : 'getFirst')](this.options.choicesMatch), true)
                }
                return false;
            case 'esc':
            case 'tab':
                this.hideChoices(true);
                break
            }
        }
        return true
    },
    setSelection: function (finish) {
        var input = this.selected.inputValue,
            value = input;
        var start = this.queryValue.length,
            end = input.length;
        if (input.substr(0, start).toLowerCase() != this.queryValue.toLowerCase()) start = 0;
        if (this.options.multiple) {
            var split = this.options.separatorSplit;
            value = this.element.value;
            start += this.queryIndex;
            end += this.queryIndex;
            var old = value.substr(this.queryIndex).split(split, 1)[0];
            value = value.substr(0, this.queryIndex) + input + value.substr(this.queryIndex + old.length);
            if (finish) {
                var space = /[^\s,]+/;
                var tokens = value.split(this.options.separatorSplit).filter(space.test, space);
                if (!this.options.allowDupes) tokens = [].combine(tokens);
                var sep = this.options.separator;
                value = tokens.join(sep) + sep;
                end = value.length
            }
        } /*this.observer.setValue(value);*/
        this.opted = value;
        if (finish || this.selectMode == 'pick') start = end;
        this.element.selectRange(start, end);
        this.fireEvent('onSelection', [this.element, this.selected, value, input])
    },
    showChoices: function () {
        var match = this.options.choicesMatch,
            first = this.choices.getFirst(match);
        this.selected = this.selectedValue = null;
        if (this.fix) {
            var pos = this.element.getCoordinates(this.relative),
                width = this.options.width || 'auto';
            this.choices.setStyles({
                'left': pos.left,
                'top': pos.bottom,
                'width': (width === true || width == 'inherit') ? pos.width : width
            })
        }
        if (!first) return;
        if (!this.visible) {
            this.visible = true;
            this.choices.setStyle('display', '');
            if (this.fx) this.fx.start(1);
            this.fireEvent('onShow', [this.element, this.choices])
        }
        if (this.options.selectFirst || this.typeAhead || first.inputValue == this.queryValue) this.choiceOver(first, this.typeAhead);
        var items = this.choices.getChildren(match),
            max = this.options.maxChoices;
        var styles = {
            'overflowY': 'hidden',
            'height': ''
        };
        this.overflown = false;
        if (items.length > max) {
            var item = items[max - 1];
            styles.overflowY = 'scroll';
            styles.height = item.getCoordinates(this.choices).bottom;
            this.overflown = true
        };
        this.choices.setStyles(styles);
        this.fix.show()
    },
    hideChoices: function (clear) {
        if (clear) {
            var value = this.element.value;
            if (this.options.forceSelect) value = this.opted;
            if (this.options.autoTrim) {
                value = value.split(this.options.separatorSplit).filter($arguments(0)).join(this.options.separator)
            } /*this.observer.setValue(value)*/
        }
        if (!this.visible) return;
        this.visible = false;
        this.observer.clear();
        var hide = function () {
            this.choices.setStyle('display', 'none');
            this.fix.hide()
        }.bind(this);
        if (this.fx) this.fx.start(0).chain(hide);
        else hide();
        this.fireEvent('onHide', [this.element, this.choices])
    },
    prefetch: function () {
        var value = this.element.value.toLowerCase(),
            query = value;
        if (this.options.multiple) {
            var split = this.options.separatorSplit;
            var values = value.split(split);
            var index = this.element.getCaretPosition();
            var toIndex = value.substr(0, index).split(split);
            var last = toIndex.length - 1;
            index -= toIndex[last].length;
            query = values[last]
        }
        if (query.length < this.options.minLength) {
            this.hideChoices()
        } else {
            if (query === this.queryValue || (this.visible && query == this.selectedValue)) {
                if (this.visible) return false;
                this.showChoices()
            } else {
                this.queryValue = query;
                this.queryIndex = index;
                if (!this.fetchCached()) this.query()
            }
        }
        return true
    },
    fetchCached: function () {
        return false;
        if (!this.options.cache || !this.cached || !this.cached.length || this.cached.length >= this.options.maxChoices || this.queryValue) return false;
        this.update(this.filter(this.cached));
        return true
    },
    update: function (tokens) {
        this.choices.empty();
        this.cached = tokens;
        if (!tokens || !tokens.length) {
            this.hideChoices()
        } else {
            if (this.options.maxChoices < tokens.length && !this.options.overflow) tokens.length = this.options.maxChoices;
            tokens.each(this.options.injectChoice ||
            function (token) {
                var choice = new Element('li', {
                    'html': this.markQueryValue(token)
                });
                choice.inputValue = token;
                this.addChoiceEvents(choice).inject(this.choices)
            }, this);
            this.showChoices()
        }
    },
    choiceOver: function (choice, selection) {
		if (!choice || choice == this.selected) return;
		if (this.selected) this.selected.removeClass('autocompleter-selected');
		this.selected = choice.addClass('autocompleter-selected');
		$(this.options.searchFormInput).value = choice.get('text');
		this.fireEvent('onSelect', [this.element, this.selected, selection]);
		if (!selection) return;
		this.selectedValue = this.selected.inputValue;
		if (this.overflown) {
			var coords = this.selected.getCoordinates(this.choices),
				margin = this.options.overflowMargin,
				top = this.choices.scrollTop,
				height = this.choices.offsetHeight,
				bottom = top + height;
			if (coords.top - margin < top && top) this.choices.scrollTop = Math.max(coords.top - margin, 0);
			else if (coords.bottom + margin > bottom) this.choices.scrollTop = Math.min(coords.bottom - height + margin, bottom)
		}
		if (this.selectMode) this.setSelection()
	},
    choiceSelect: function (choice) {
		if (choice) this.choiceOver(choice);
		this.setSelection(true);
		this.queryValue = false;
		this.hideChoices();
		var text = encodeURIComponent(choice.get('text')).toLowerCase();
		if(parseInt(choice.getFirst('a').get('rel'))==1){
			new Request.JSON({
				url : this.options.urlBase+'?wt=json&rows=1&q=lc_title:"'+text+'"',
				onComplete : function(obj) {location.href = obj.response.docs[0].url.substring(obj.response.docs[0].url.indexOf('rte.ie')+6)}
			}).send();
		}else{
			this.formSubmit('"'+text+'"');
		}
	},
	formSubmit: function(q){
		if(!q) q = encodeURIComponent($(this.options.searchFormInput).value);
		if (q != '') {
			window.location.href = this.options.searchPageUrl + "?query=" + q;
		}
	},
    filter: function (tokens) {
        return (tokens || this.tokens).filter(function (token) {
            return this.test(token)
        }, new RegExp(((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp(), (this.options.filterCase) ? '' : 'i'))
    },
    markQueryValue: function (str) {
        return (!this.options.markQuery || !this.queryValue) ? str : str.replace(new RegExp('(' + ((this.options.filterSubset) ? '' : '^') + this.queryValue.escapeRegExp() + ')', (this.options.filterCase) ? '' : 'i'), '<span class="autocompleter-queried">$1</span>')
    },
    addChoiceEvents: function (el) {
        return el.addEvents({
            'mouseover': this.choiceOver.bind(this, [el]),
            'click': this.choiceSelect.bind(this, [el])
        })
    }
});
Autocompleter.Ajax = {};
Autocompleter.Ajax.Base = new Class({
    Extends: Autocompleter.Base,
    options: {
        postVar: 'value',
        postVarPrefix: '',
        postData: {},
        ajaxOptions: {},
        onRequest: $empty,
        onComplete: $empty
    },
    initialize: function (element, options) {
        this.parent(element, options);
        var indicator = document.id(this.options.indicator);
        if (indicator) {
            this.addEvents({
                'onRequest': indicator.show.bind(indicator),
                'onComplete': indicator.hide.bind(indicator)
            }, true)
        }
    },
    query: function () {
        var data = $unlink(this.options.postData);
        data[this.options.postVar] = this.options.postVarPrefix + this.queryValue;
        this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
        this.request.send({
            'data': data
        })
    },
    queryResponse: function () {
        this.fireEvent('onComplete', [this.element, this.request, this.response])
    }
});
Autocompleter.Ajax.Json = new Class({
    Extends: Autocompleter.Ajax.Base,
    initialize: function (el, url, options) {
        this.parent(el, options);
        this.request = new Request.JSON($merge({
            'url': url,
            'link': 'cancel'
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this))
    },
    queryResponse: function (response) {
        this.parent();
        this.update(response)
    }
});
Autocompleter.Ajax.Xhtml = new Class({
    Extends: Autocompleter.Ajax.Base,
    initialize: function (el, url, options) {
        this.parent(el, options);
        this.request = new Request.HTML($merge({
            'url': url,
            'link': 'cancel',
            'update': this.choices
        }, this.options.ajaxOptions)).addEvent('onComplete', this.queryResponse.bind(this))
    },
    queryResponse: function (tree, elements) {
        this.parent();
        if (!elements || !elements.length) {
            this.hideChoices()
        } else {
            this.choices.getChildren(this.options.choicesMatch).each(this.options.injectChoice ||
            function (choice) {
                var value = choice.innerHTML;
                choice.inputValue = value;
                this.addChoiceEvents(choice.set('html', this.markQueryValue(value)))
            }, this);
            this.showChoices()
        }
    }
});
Autocompleter.JSONP = new Class({
    Extends: Autocompleter.Ajax.Json,
    options: {
        postVar: 'query',
        postVarPrefix: '',
        jsonpOptions: {},
        minLength: 1
    },
    initialize: function (el, url, options) {
        this.url = url;
        this.setOptions(options);
        this.parent(el, options)
    },
    query: function () {
        var data = $unlink(this.options.jsonpOptions.data || {});
        data[this.options.postVar] = this.options.postVarPrefix + this.queryValue;
        this.jsonp = new Request.JSONP($merge({
            url: this.url,
            data: data
        }, this.options.jsonpOptions));
        this.jsonp.addEvent('onComplete', this.queryResponse.bind(this));
        this.fireEvent('onRequest', [this.element, this.jsonp, data, this.queryValue]);
        this.jsonp.send()
    },
    queryResponse: function (response) {
        this.parent();
        var data = (this.options.filter) ? this.options.filter.run([response], this) : response;
        this.update(data)
    }
});
Autocompleter.JsonP = Autocompleter.JSONP;
var Observer = new Class({
    Implements: [Options, Events],
    options: {
        periodical: false,
        delay: 1000
    },
    initialize: function (el, onFired, options) {
        this.setOptions(options);
        this.addEvent('onFired', onFired);
        this.element = document.id(el) || $$(el);
        this.boundChange = this.changed.bind(this);
        this.resume()
    },
    changed: function () {
        var value = this.element.get('value');
        if ($equals(this.value, value)) return;
        this.clear();
        this.value = value;
        this.timeout = this.onFired.delay(this.options.delay, this)
    },
    setValue: function (value) {
        this.value = value;
        this.element.set('value', value);
        return this.clear()
    },
    onFired: function () {
        this.fireEvent('onFired', [this.value, this.element])
    },
    clear: function () {
        $clear(this.timeout || null);
        return this
    },
    pause: function () {
        $clear(this.timeout);
        $clear(this.timer);
        this.element.removeEvent('keyup', this.boundChange);
        return this
    },
    resume: function () {
        this.value = this.element.get('value');
        if (this.options.periodical) this.timer = this.changed.periodical(this.options.periodical, this);
        else this.element.addEvent('keyup', this.boundChange);
        return this
    }
});
var $equals = function (obj1, obj2) {
    return (obj1 == obj2 || JSON.encode(obj1) == JSON.encode(obj2))
};
