//Function to load in external files
function loadFile(filename, filetype) {
    var fileref;
    if (filetype == "js") { //if filename is a external JavaScript file
        fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", filename);
    }

    else if (filetype == "css") { //if filename is an external CSS file
        fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }

    if (typeof fileref != "undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
}

var webtape = {

	errorMessage: function(where, report){
		
		if(!report) {
			report = 'Oops, something went wrong here...';
		}
		
		where.fade('out')
		.set('text', report)
		.addClass('error')
		.fade('in')
		.highlight();
	},
	
	successMessage: function(where, report){
		
		where.fade('out');
		
		if(!report) {
			report = 'Whoa, something actually worked!';
		}
		
		if(where.hasClass('error')) {
			where.removeClass('error').setStyle('background-color','#FFFFCC');
		}
		
		where.set('text', report)
			.addClass('confirm')
			.fade('in')
			.highlight()
			.setStyle('background-color','#FFFFCC');
				
	},
	
	isEmail: function(email) {
		
		var emailToTest,
			regEx = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		
		if(typeof email == 'object'){
			emailToTest = email.get('value'); 
		} else {
			emailToTest = email;
		}
		
		
		return regEx.test(emailToTest);
		
	},
	
	isTrue: function(input) {
		
		if(input =='' && input == 'undefined' && typeof input == 'undefined' && input == ' ' && input == null) {
			return false;
		} else {
			return true;
		}
		
	},
	
	initToolbox: function() {
		if ($('toolbox') && $('init_toolbox')) {
		    new mootabs('toolbox');
			var toolboxslide = new Fx.Slide('toolbox');
			toolboxslide.hide();
			$('init_toolbox').addEvent('click', function (e) {
			    e.stop();
			    toolboxslide.toggle();
			});		    
		}
	},
	
	reportError: function(errorMsg, url, lineNumber) {
				
		var queryParams = {
			'error_msg': errorMsg,
			'url': url,
			'line_number': lineNumber,
			'location': window.location.href,
			'action': 'report_error'
		};
		
		new Request({
			url: 'http://onwebtape.com/process.php',
			method: 'post'
		}).send(Hash.toQueryString(queryParams));
		
		return false;

	}

};

window.webtape = webtape;
//window.onerror = webtape.reportError;

function errorMessage(where,report) {
	
	if(!report) {
		report = 'Oops, something went wrong here...';
	}
	
	where.fade('out')
		.set('text', report)
		.addClass('error')
		.fade('in')
		.highlight();
}

function successMessage(where,report) {

	where.fade('out');
	
	if(where.hasClass('error')) {
		where.removeClass('error').setStyle('background-color','#FFFFCC');
	}
	
	where.set('text', report)
		.addClass('confirm')
		.fade('in')
		.highlight()
		.setStyle('background-color','#FFFFCC');
}

//Do the slider
function generateSlider() {
    if ($('myElement') !== null && $('knob') !== null) {
        var el = $('myElement');
        var knob = $('knob');
        var slide = new Slider(el, knob, {
            steps: 20,
            offset: 9,
            mode: 'vertical',
            onChange: function (value, who) {
                $('counter').set('html', value);
                $('fielder').set('value', value);
            },
            onComplete: function (step) {
                var log = $('log_res').empty().addClass('ajax-loading');
                $('myForm').set('send', {
                    onComplete: function (response) {
                        log.removeClass('ajax-loading');
                        log.set('html', response);
                    }
                });
                $('myForm').send();
            }
        });

        $('who').addEvent('change', function () {
            var log = $('log_res').empty().addClass('ajax-loading');
            $('myForm').set('send', {
                onComplete: function (response) {
                    log.removeClass('ajax-loading');
                    log.set('html', response);
                }
            });

            $('myForm').send();
        });

        slide.set(10);
    }
}

function generateTabs() {
    var mootabs = new Class({
        Implements: Options,
        options: {
            width: '380px',
            height: '310px',
            changeTransition: 'none',
            duration: 1000,
            mouseOverClass: 'active',
            activateOnLoad: 'updates',
            useAjax: true,
            ajaxUrl: '../tabs.php',
            ajaxOptions: {
                method: 'get'
            },
            ajaxLoadingText: '<' + 'div' + 'class="loading"&gt;' + '&lt;' + 'img' + 'src="http://demos111.mootools.net/demos/Group/spinner.gif" alt="loading..." /&gt;' + '&lt;' + 'br' + ' /&gt;loading' + '&lt;/' + 'div' + '&gt;',
            evalScripts: true

        },
        initialize: function (element, options) {
            this.setOptions(options);

            this.el = $(element);
            this.elid = element;

            this.el.setStyles({
                height: this.options.height,
                width: this.options.width
            });

            this.titles = $$('#' + this.elid + ' ul.mootabs_title li');
            this.panelHeight = this.el.getSize().y - (this.titles[0].getSize().y + 4);
            this.panels = $$('#' + this.elid + ' .mootabs_panel');

            this.panels.setStyle('height', this.panelHeight);

            this.titles.each(function (item) {
                item.addEvent('click', function () {
                    item.removeClass(this.options.mouseOverClass);
                    this.activate(item);
                }.bind(this));

                item.addEvent('mouseover', function () {
                    if (item != this.activeTitle) {
                        item.addClass(this.options.mouseOverClass);
                    }
                }.bind(this));

                item.addEvent('mouseout', function () {
                    if (item != this.activeTitle) {
                        item.removeClass(this.options.mouseOverClass);
                    }
                }.bind(this));
            }.bind(this));

            if (this.options.activateOnLoad != 'none') {
                if (this.options.activateOnLoad == 'first') {
                    this.activate(this.titles[0], true);
                }
                else {
                    this.activate(this.options.activateOnLoad, true);
                }
            }
        },

        activate: function (tab, skipAnim) {
            if (!$defined(skipAnim)) {
                skipAnim = false;
            }
            if ($type(tab) == 'string') {
                myTab = $$('#' + this.elid + ' ul li').filter('[title=' + tab + ']');
                tab = myTab;
            }

            if ($type(tab) == 'element') {
                var newTab = tab.get('title');
                this.panels.removeClass('active');

                this.activePanel = this.panels.filter('[id=' + newTab + ']');
                this.activePanel.addClass('active');

                if (this.options.changeTransition != 'none' && skipAnim === false) {
                    this.panels.filter('[id=' + newTab + ']').setStyle('height', 0);
                    var changeEffect = new Fx.Elements(this.panels.filter('[id=' + newTab + ']'), {
                        duration: this.options.duration,
                        transition: this.options.changeTransition
                    });
                    changeEffect.start({
                        '0': {
                            'height': [0, this.panelHeight]
                        }
                    });
                }

                this.titles.removeClass('active');

                tab.addClass('active');

                this.activeTitle = tab;

                if (this.options.useAjax) {
                    this._getContent();
                }
            }
        },

        _getContent: function () {
            this.activePanel.set('html', this.options.ajaxLoadingText);
            var panel = this.activePanel;
            var requestURL = this.options.ajaxUrl + '?tab=' + this.activeTitle.get('title');
            var tabRequest = new Request.HTML({
                url: requestURL,
                onSuccess: function (html) {
                    panel.set('html', '');
                    panel.adopt(html);
                },
                onFailure: function () {
                    panel.set('text', 'The request failed.');
                }
            });
            tabRequest.send();
        },

        addTab: function (title, label, content) {
            //the new title
            var newTitle = new Element('li', {
                'title': title
            });
            newTitle.appendText(label);
            this.titles.include(newTitle);
            $$('#' + this.elid + ' ul').adopt(newTitle);
            newTitle.addEvent('click', function () {
                this.activate(newTitle);
            }.bind(this));

            newTitle.addEvent('mouseover', function () {
                if (newTitle != this.activeTitle) {
                    newTitle.addClass(this.options.mouseOverClass);
                }
            }.bind(this));
            newTitle.addEvent('mouseout', function () {
                if (newTitle != this.activeTitle) {
                    newTitle.removeClass(this.options.mouseOverClass);
                }
            }.bind(this));
            //the new panel
            var newPanel = new Element('div', {
                'style': {
                    'height': this.options.panelHeight
                },
                'id': title,
                'class': 'mootabs_panel'
            });
            if (!this.options.useAjax) {
                newPanel.set('html', content);
            }
            this.panels.include(newPanel);
            this.el.adopt(newPanel);
        },

        removeTab: function (title) {
            if (this.activeTitle.title == title) {
                this.activate(this.titles[0]);
            }
            $$('#' + this.elid + ' ul li').filter('[title=' + title + ']').remove();

            $$('#' + this.elid + ' .mootabs_panel').filter('[id=' + title + ']').remove();
        },

        next: function () {
            var nextTab = this.activeTitle.getNext();
            if (!nextTab) {
                nextTab = this.titles[0];
            }
            this.activate(nextTab);
        },

        previous: function () {
            var previousTab = this.activeTitle.getPrevious();
            if (!previousTab) {
                previousTab = this.titles[this.titles.length - 1];
            }
            this.activate(previousTab);
        }
    });
}

//Generate the Toolbox
function generateToolbox() {
    generateTabs();
    if ($('toolbox') !== null) {
        myTabs1 = new mootabs('toolbox');
        if ($('init_toolbox') !== null) {
            var toolboxslide = new Fx.Slide('toolbox');
            toolboxslide.hide();
            $('init_toolbox').addEvent('click', function (e) {
                e.stop();
                toolboxslide.toggle();
            });
        }
    }
}

function addToggler(trigger,which) {
	var toggler = new Fx.Slide(which);
	toggler.hide();
	$(trigger).addEvent('click', function(e){ e.stop(); toggler.toggle(); });
}

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}
/*
var MyFB = {
	
		init: function(){
		
			FB.init({
				appId  : '826faa3f8c6fbeabfe497e4333494f3a',
				status : true, // check login status
				cookie : true, // enable cookies to allow the server to access the session
				xfbml  : true  // parse XFBML
			});
			
			return this;
		
		},
		
		loggedIn: function(){
					
			$(document.body).getElements('.facebook').setStyle('display', 'block');
		
			$$('input[type=checkbox]').each(function(el) {
				el.set('checked', true); 
			});
		
			$('user').innerHTML = 'Okay, <fb:name uid="loggedinuser" useyou="false"></fb:name>, you are connected to Facebook!';
							
			FB.XFBML.parse();
		},
		
		loggedOut: function(){
		
			$('user').innerHTML = 'Log into facebook...';
			
			FB.XFBML.parse();
		
		},
		
		checkStatus: function(){
			
			var that = this;
			
			FB.getLoginStatus(function(response) {
	
				if (response.session) {
					that.loggedIn();
				} else {
					that.loggedOut();
				}
			});
			
		},

		isLoggedIn: function(){
			var res;
			
			FB.getLoginStatus(function(response) {
	
				if (response.session) {
					res = true;
				} else {
					res = false;
				}
	        });
	        
	        return res;	
        
		},
		
		getUserID: function(){
			
			var sesh = FB.getSession();
			
			return sesh.uid;
			
		},
				
		publishStream: function(params){
			
			FB.ui(
			
			{
				 method: 'stream.publish',
				 message: params.message,
				 attachment: {
				   name: params.title,
				   caption: params.caption,
				   description: params.description,
				   href: params.link
				 },
				 action_links: [params.actionLink],
				 user_prompt_message: params.prompt
			},
			
			params.callback
			
			);
			
		},
		
		uploadManagerToggleState: function(isLoggedIn) {
			
			var display;
			
			if(isLoggedIn) {
				display = 'block';
			} else {
				display = 'none';
			}
			
			$(document.body).getElements('.facebook').setStyle('display', display);
					
			$$('input[type=checkbox]').each(function(el) {
				el.set('checked', isLoggedIn); 
			});
			
		},
		
		uploadManager: function() {
			
			var that = this;
			
			FB.getLoginStatus(function(response) {
	
				if(response.session) {
					
					var self = that;
					
					FB.logout(function(){
				
						$(document.body).getElements('.facebook').setStyle('display', 'none');
					
						$$('input[type=checkbox]').each(function(el) {
							el.set('checked', false); 
						});
					
					});
					
				} else {
					
					var self = that;
					
					FB.Event.subscribe('auth.login', function(response) {
					  $(document.body).getElements('.facebook').setStyle('display', 'block');
					
						$$('input[type=checkbox]').each(function(el) {
							el.set('checked', true); 
						});
					});
					
					FB.Event.subscribe('auth.logout', function(response) {
					  $(document.body).getElements('.facebook').setStyle('display', 'none');
					
						$$('input[type=checkbox]').each(function(el) {
							el.set('checked', false); 
						});
					});

				}
	        });
						
		}
		
};*/
