if(!window.console) window.console = { log: function(msg) {}, error: function(msg) {} };
var Boomster = {
	currModal: null,
	//Show the jquery, dom, or text object in a popup
	containerClassName: 'basicPopupContainer',
	contentClassName: 'basicPopupContents',
	modal: function(toAdd, popupCfg) {
        if(!popupCfg) popupCfg = {};
		if(toAdd) {
			//Make sure all popups are wrapped with the proper styles
			if(!toAdd.nodeName) { //dom
                var html = toAdd;
                toAdd = document.createElement('div');
                toAdd.innerHTML = html;
			}
			this.currModal = new Ext.Window(Ext.apply({
                html: toAdd.innerHTML,
                title: 'Test title',
                modal: true,
                closable: true,
                cls: 'modal',
                shim: true,
                draggable: false,
                listeners: {
                    destroy: Boomster.showFlash
                }
            }, popupCfg));
            Boomster.hideFlash();
            this.currModal.show();
		} else {
			console.log('No contents for popup');
		}
	},
    hideFlash: function() {
        $('object').css('visibility', 'hidden');
    },
    showFlash: function() {
        $('object').css('visibility', 'visible');
    },
	getAjaxData: function(toSend) {
		if(toSend.type == 'POST') {
			toSend.data['contentOnly'] = true;
		}
		return toSend;
	},
	serializeForm: function(form) {
		var retVal = {};
		for(var i = 0; i < form.elements.length; i ++) {
			var val = '';
			var add = true;
			var node = form.elements[i];
			switch(node.nodeName.toLowerCase()) {
				case 'input':
					switch(node.type.toLowerCase()) {
						case 'radio':
						case 'checkbox':
							if(node.checked) val = node.value;
							break;
						default:
							val = node.value;
							break;
					}
					break;
				case 'select':
					val = node.options[node.selectedIndex].value;
					break;
				case 'textarea':
					val = node.innerHTML;
					break;
				default:
					add = false;
					break;
			}
			if(add && node.name != '' && node.name.toString() != 'undefined') {
				if(val != '' && retVal[node.name] && retVal[node.name].toString() != 'undefined') retVal[node.name] += ',' + val;
				else retVal[node.name] = val;
			}
		}
		//for(key in retVal) console.log(key + ' = ' + retVal[key]);
		return retVal;
	},
	confirmBlock: function(name) {
		return confirm("If you block " + name + ", you will no longer receive messages or contact invitations from this user. You will be able to un-block them at any time from your account page.");
	}
};
Boomster.validate = {
	_val: function(obj) {
		return (obj === null || obj.toString() == 'undefined')?'':obj;
	},
	email: function(address) {
		return Boomster.validate._val(address).search(/^[a-zA-Z.-_]+?@[a-zA-Z.-_]+\.[a-zA-Z]{2,4}$/) === 0;
	}
}
Boomster.widgets = {
	makeSearch: function(node, options) {
		node = Ext.get(node).dom;
		var vals = [];
		for(var i = 0; i < node.options.length; i ++) {
			vals[vals.length] = [node.options[i].value, node.options[i].innerHTML];
		}
		var store = new Ext.data.SimpleStore({
			fields: ['value', 'label'],
			data : vals
		});
		store.filter = function(property, value, anyMatch, caseSensitive){
			var fn = this.createFilterFn(property, value, true, false);
			return fn ? this.filterBy(fn) : this.clearFilter();
		};

		var container = document.createElement('div');
		var input = document.createElement('input');
		input.type = 'text';
		input.id = node.id;
		input.name = node.name;
		container.appendChild(input);
		node.id = "";
		node.parentNode.insertBefore(container, node);
		node.parentNode.removeChild(node);
        options.store =  store;
        options.triggerAction =  'all';
        options.hideTrigger = true;
        options.selectOnFocus = true;
        options.typeAhead =  false;
        options.displayField =  'label';
        options.applyTo =  input.id;
        options.mode =  'local';

		var combo = new Ext.form.ComboBox(options);
		combo.findRecord = function(field, value, startIndex) {	};
		return combo;
	},
    /**
    * Add an inner label to inputs or text fields.
    * It gets removed when typing starts, replced when the field is empty, and cleared when the form is submitted.
    * @param node string The Jquery selector for the target node (only one can be affected at a time right now)
    * @param text string The inner label text
    */
    innerLabel: function(node, text) {
        $(node).bind('focus', function() {
            if($(node).attr('value') == text)
                $(node).removeClass('innerLabel').attr('value', '');
        });
        $(node).bind('blur', function() {
            if($(node).attr('value') == '')
                $(node).addClass('innerLabel').attr('value', text);
        });
        $($(node)[0].form).bind('submit', function() {
            if($(node).attr('value') == text)
                $(node).attr('value', '');
        })
        $(node).attr('value', text);
        $(node).addClass('innerLabel');
    },
    inputSwapBack: function(node) {
        var original = $(node).attr('value');
        $(node).bind('focus', function() {
           this.select();
        });
        $(node).bind('keyup', function(e) {
            if(e.keyCode == 27) {
                this.value = original;
            }
        });
    }
}
Boomster.searchBox = {
    setDefault: function(id) {
        var node = Ext.get(id);
        var location = window.location.toString();
        var mode = location.replace(/.*?\w\/(\w+)\/?.*/, '$1');
        Boomster.searchBox.setMode(mode);
    },
    setMode: function(mode) {
        var changed = true;
        switch(mode) {
            case "people":
            case "meet":
                $("#search-text").val("Enter name, interest, location or industry");
                $("#search-form").attr("action", "/people/search");
                value = 'people';

                break;
            case "community":
            case "discuss":
                $("#search-text").val("Enter groups, discussions, or questions");
                $("#search-form").attr("action", "/discuss/search");
                value = 'community';
                break;

            case "resources":
            case "learn":
                $("#search-text").val("Enter article, audio, video or tags");
                $("#search-form").attr("action", "/resources/search");
                value = 'resources';
                break;
            default:
                changed = false;
                break;
        }
        if(changed) {
            Ext.each(Ext.get('search-type').dom.options, function(item, index, source) {
                item.selected = (item.value == value);
            });
        }

    }
}
Boomster.home = {
	getWelcomeScreen: function(welcomeHtml) {
		$("")
		Boomster.modal(welcomeHtml);
	}
}

Boomster.resources = {
	getTranscript: function () {
		Boomster.modal(document.getElementById('transcript').innerHTML, {
            width: 500,
            height: 500,
            title: 'Transcript',
            autoScroll: true
        });
        return false;
	},
	getEmailLinkForm: function(form) {
		try {
			$.ajax(Boomster.getAjaxData({
				url: form.action,
				type: 'POST',
				dataType: 'html',
				data: Boomster.serializeForm(form),
				timeout: 10000,
				error: Boomster.resources._emailLinkError,
				success: function(content) { Boomster.modal(content, { width: 400, title: 'Share this article with a friend' }) }//Boomster.modal
			}));
		} catch(e) { console.log(e, 'error') }
		return false;
	},
	emailLink: function() {
		try {
			var form = $("#emailLinkForm").get(0);
			var data = Boomster.serializeForm(form);
			var email = data['email'];
			//for(key in data) console.log(key + " = " + data[key]);

			if(!Boomster.validate.email(email)) {
				Boomster.resources._emailLinkMessage('Please enter a valid email address', 'error');
			} else if(!data['name']) {
				Boomster.resources._emailLinkMessage('Please enter your name', 'error');
			} else {
				$.ajax(Boomster.getAjaxData({
				    url: form.action,
				    type: 'POST',
				    dataType: 'json',
					data: data,
				    timeout: 10000,
				    error: Boomster.resources._emailLinkError,
				    success: Boomster.resources._emailLinkResponse
				}));
			}
		} catch(e) { Boomster.resources._emailLinkMessage(e, 'error') }
		return false;
	},
	_emailLinkResponse: function(response) {
		Boomster.resources._emailLinkMessage(response.message, response.messageType);
	},
	_emailLinkMessage: function(text, type) {
		if(type == 'error') text = '<div class="error">' + text + '</div>';

		$("#emailLinkForm .response").hide("slow", function() {
			this.innerHTML = text;
			$(this).show('slow');
		});
	},
	_emailLinkError: function(request) {
		// create a modal dialog with the data
		var message = (typeof request == 'object')?'There was an error processing your request':request;
		Boomster.resources._emailLinkMessage(message, 'error');
	}
};
var Slider = function(container, itemsPerPage, controlsContainer) {
    this.ItemsPerPage = itemsPerPage;
    if(container.nodeName) {
        this.Outer = $(container);
        this.Init();
    } else {
        //Assume it's an ID
        var me = this;
        $(document).ready(function() {
            me.Outer = $('#' + container);
            me.ControlsContainer = $('#' + controlsContainer);
            me.Init();
        });
    }
}
Slider.prototype = {
    CurrPage: null,
    Outer: null,
    Inner: null,
    ControlsContainer: null,
    ItemsPerPage: null,
    ItemWidth:null,
    MaxPageIndex: null,
    PageWidth: null,
    OnAuto: true,
    DelayTime: 8000,

    Init: function() {
        //Initialize and get the width of the outer container
        var maxWidth = this.Outer.width();
        this.Outer.css('overflow', 'hidden');

        //Initialize the inner container
        this.Inner = this.Outer.find(".sliderInner");
        this.Inner.width(10000);
        //this.Inner.height(this.Outer.height());

        //Initialize the items
        var items = this.Inner.find(".item");
        items.css('float', 'left');
        this.ItemWidth = Math.floor(maxWidth / this.ItemsPerPage);
        var realWidth = this.ItemWidth;
        realWidth -= items.css('margin-left').replace('px', '') * 1;
        realWidth -= items.css('margin-right').replace('px', '') * 1;
        items.width(realWidth);

        //Initizalize page values
        this.MaxPageIndex = Math.ceil(items.length / this.ItemsPerPage) - 1;
        this.PageWidth = this.ItemWidth * this.ItemsPerPage;

        //Set up the controls
        var me = this;
        $('<span class="previous">&lt;</span>').click(function() {
            me.OnAuto = false;
            me.Previous();
        }).appendTo(this.ControlsContainer);
        for(var i = 0; i <= this.MaxPageIndex; i ++) {
            $('<span class="page">' + (i + 1) + '</span>').click(function() {
                me.OnAuto = false;
                me.SwitchTo((this.innerHTML * 1) - 1, true);
            }).appendTo(this.ControlsContainer);
        }
        $('<span class="next">&gt;</span>').click(function() {
            me.OnAuto = false;
            me.Next();
        }).appendTo(this.ControlsContainer);

        this.SwitchTo(0, false);

        setTimeout(function() {
            me.Autoplay();
        }, this.DelayTime);

    },
    Autoplay: function() {
        if(this.OnAuto) {
            this.Next();
            var me = this;
            setTimeout(function() {
                me.Autoplay();
            }, this.DelayTime);
        }
    },
    SwitchTo: function(pageIndex, animateChange) {
        this.CurrPage = pageIndex;
        var newPos = pageIndex * this.PageWidth;
        //console.log('%d, %d, %d', pageIndex, this.PageWidth, newPos);
        var speed = (this.OnAuto)?2000:'medium';
        if(animateChange) {
            this.Outer.animate({
                scrollLeft: newPos
            }, speed);
        } else {
            this.Outer.scrollLeft(newPos);
        }
        this.UpdateControls();
    },
    Previous: function() {
        if(this.CurrPage > 0) this.SwitchTo(this.CurrPage - 1, true);
        else this.JumpToEnd();
    },
    Next: function() {
        if(this.CurrPage < this.MaxPageIndex) this.SwitchTo(this.CurrPage + 1, true);
        else this.JumpToBeginning();
    },
    JumpToBeginning: function() {
        this.JumpTo(0);
    },
    JumpToEnd: function() {
        this.JumpTo(this.MaxPageIndex);
    },
    JumpTo: function(pageIndex) {
        var me = this;
        this.Inner.fadeOut('fast', function() {
            //Hack to get around JQuery's use of display:none for fading out
            me.Inner.css('visibility', 'hidden');
            me.Inner.css('display', 'block');
            me.SwitchTo(pageIndex, false);
            me.Inner.css('display', 'none');
            me.Inner.css('visibility', 'visible');
            me.Inner.fadeIn('fast');
        });
    },
    UpdateControls: function() {
        var me = this;
        this.ControlsContainer.find('span').each(function() {
            if(this.innerHTML == (me.CurrPage + 1) + '') $(this).addClass('active');
            else $(this).removeClass('active');
        });
    }
}
