/*
Script: sharethis.js
	Contains <sharethis>

Author:
	Alan Roemen

Class: ShareThis
	<No Description>

Options:
	baseURL : URL of script. Default: false
	shareIMG : URL of Image. Default: false
	imgAlign : Image alignment around text. Options 'off' or 'both' or 'right' or 'left'. Default: 'off'
	timeout: Amount of time sharethis window will remain open. Default: false (false means it will timeout)
	duration: Amount of time to transition pop window opening. Default: 500
	offsets: PopUp offsets. Default: {'x': 0, 'y': 18}
	defaults: If set to true, will use page title and page url. Default: false
	shareTXT : Text to display in WebPage. Default: 'Share This Page'
	subject: Message default subject. Default: 'Check out this website'
	message: Message default message body. Default: 'I found a website that I thought you might find interesting. '
	className : Class name to CSS class. Default: 'ShareThis'

Events:
	onShow - optionally you can alter the default onShow behaviour with this option (like displaying a fade in effect);
	onHide - optionally you can alter the default onHide behaviour with this option (like displaying a fade out effect);
*/
var ShareThis = new Class({

	options: {
		onShow: function(el){
			if(window.ie6) el.setStyles({'visibility': 'visible', 'opacity': 1});
			else el.effects({duration: this.options.duration, transition: Fx.Transitions.quadInOut}).custom({'opacity': [0, 1.0]});
		},
		onHide: function(el){
			el.setStyle('visibility', 'hidden');
		},
		baseURL: false,
		shareIMG: false,
		imgAlign: 'off',
		timeout: false,
		duration: 500,
		offsets: {x: 0, y: 18},
		defaults: false,
		shareTXT: 'Share This Page',
		subject: 'Check out this website',
		message: 'I found a website that I thought you might find interesting. ',
		globalClass: true,
		className: 'ShareThis',
		scriptName: 'sharethis',
		active_tab: 0
	},

	initialize: function(){
		var options, elements;
		$each(arguments, function(argument, i){
			switch($type(argument)){
				case 'object': options = argument; break;
				default:
					if (!elements) elements = $$(argument);
					else elements = elements.concat($$(argument));
			}
		});
		this.fields = elements;
		this.setOptions(options);

		// Get script base path
		if(!this.options.baseURL) {
			elements = document.getElementsByTagName('script');
			for (var i=0; i<elements.length; i++) {
				if (elements[i].src && (elements[i].src.indexOf(this.options.scriptName+'.js') != -1)) {
					var src = elements[i].src;
					this.options.baseURL = src.substring(0, src.lastIndexOf('/'));
					break;
				}
			}
			// Get document base path
			this.documentBasePath = document.location.href;
			if (this.documentBasePath.indexOf('?') != -1)
				this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.indexOf('?'));
			this.documentBasePath = this.documentBasePath.substring(0, this.documentBasePath.lastIndexOf('/'));
			if (this.options.baseURL.indexOf('://') == -1 && this.options.baseURL.charAt(0) != '/')
				this.options.baseURL = this.documentBasePath + "/" + this.options.baseURL;
		}

		// Gets ShareIMG
		if(!this.options.shareIMG) this.options.shareIMG = this.options.baseURL + '/' + this.options.scriptName + '.gif';

		// Setup pages sharethis fields
		this.setfields();

		// Adds Stylesheet
		if(this.options.globalClass!==false) new Asset.css(this.options.baseURL + '/' + this.options.scriptName + '.css', {id: 'style'});

		// Setup Ajax
		this.ajaxURL = this.options.baseURL + '/'+this.options.scriptName+'.php';
		this.active = false;

		// Create Main DIV & Wrapper
		this.sharebox = new Element('div', {
			'class': this.options.className,
			'styles': {
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'visibility': 'hidden'
			}
		}).inject($$('body')[0]);
		this.wrapper = new Element('div').injectInside(this.sharebox);
	},

	setfields: function(){
		var temp, pageTitle, pageLink;
		pageTitle = $$('title')[0].innerHTML;
		pageLink = location.href;
		$each(this.fields, function(field,i){
			temp = {
				'title': (field.title&&!this.options.defaults?field.title:pageTitle),
				'link': (field.innerHTML&&!this.options.defaults?field.innerHTML:pageLink),
				'element': field
			}
			//this.fields[i].empty();
			this.fields[i] = temp;
			this.img = new Element('img',{
				'src':this.options.shareIMG,
				'styles': {
					'cursor': 'pointer'
				},
				'events': {
					'click': (function(e){
						e = new Event(e).stop();
						this.start(i);
					}).bindWithEvent(this)}
				});
			if((this.options.imgAlign!='off' && this.options.imgAlign!='right') || this.options.imgAlign=='both')
				this.img.injectInside(this.fields[i].element);

			if (false !== this.options.shareTXT)
				this.fields[i].element.setHTML(this.options.shareTXT);
			this.fields[i].element.setStyle('cursor','pointer');
			this.fields[i].element.addEvent('click', function(e){
				e = new Event(e).stop();
				this.start(i);
			}.bindWithEvent(this));

			if((this.options.imgAlign!='off' && this.options.imgAlign == 'right') || this.options.imgAlign=='both')
				this.img.injectInside(this.fields[i].element);
		}.bind(this));
	},

	build: function() {
		this.wrapper.empty();
		
		// build main ShareThis div
		this.header = new Element('div',{'class':'head'}).injectInside(this.wrapper);
		this.body = new Element('div',{'class':'body'}).injectInside(this.wrapper);
		
		// setup close link
		this.close = new Element('a',{
			'href': '#',
			'class': 'close',
			'events': {
				'click': (function(e){
					new Event(e).stop();
					this.end();
				}).bindWithEvent(this)}
		}).setHTML('close').injectInside(this.header);
		
		// setup tabs
		this.tablinks = [
			new Element('li',{
			'events': {
				'click': (function(){
					if(this.alert_msg) { this.alert_msg.remove(); this.alert_msg=false; }
					this.activeTab(0);
					this.toAddress.focus();
				}).bindWithEvent(this)}
			}).setHTML('Email'),
			new Element('li',{
			'events': {
				'click': (function(){
					this.activeTab(1);
				}).bindWithEvent(this)}
			}).setHTML('Social Web')
		];
		this.tablinks[this.options.active_tab].addClass('selected');
		this.tabs = new Element('ul')
			.adopt(this.tablinks)
			.inject(this.header);
		this.tabs.inject(this.header);
		
		// setup body divs
		this.bodydivs = [
			new Element('div',{'class':'email'}).adopt([
				new Element('fieldset').adopt([
					new Element('legend').setHTML('Email It')
				]),// </fieldset
				new Element('ul').adopt([
					new Element('li').adopt([
						new Element('label').setHTML('Recipient(s) Address'),
						(this.toAddress = new Element('input',{'type':'text'})),
						new Element('label', {'class': 'small-label'}).setHTML('(Multiple: friend1@site.com, friend2@site.com)')
					]),// </li
					new Element('li').adopt([
						new Element('label').setHTML('Your Name'),
						(this.senderName = new Element('input',{'type':'text'}))
					]),// </li
					new Element('li').adopt([
						new Element('label').setHTML('Your Email Address'),
						(this.senderAddress = new Element('input',{'type':'text'}))
					]),// </li
					new Element('li').adopt([
						new Element('label').setHTML('Subject'),
						(this.subject = new Element('input',{'type':'text','value':this.options.subject}))
					]),// </li
					new Element('li').adopt([
						new Element('label').setHTML('Message'),
						(this.message = new Element('textarea').setHTML(this.options.message))
					]),// </li
					new Element('li').adopt([
						new Element('label').setHTML('<strong>Only</strong> enter the black letters in the image'),
						(this.captcha = new Element('input',{'type': 'text','class': 'captcha'})),
						(this.captchaIMG = new Element('img',{
							'src': this.options.baseURL+'/images/captcha.php',
							'title': 'Click the image to obtain a new key',
							'styles': {'cursor': 'pointer'},
							'events': {
								'click': (function(e){
									new Event(e).stop();
									this.reloadCAPTCHA();
									this.captcha.focus();
								}).bindWithEvent(this)
							}
						}))
					]),// </li
					new Element('li').adopt([
						new Element('button',{'events': {'click': this.sendEmail.bind(this)}}).setHTML('Send')
					])// </li
				])// </ul
			]),// </div.email
			new Element('ul',{'class':'social'}).adopt([
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=facebook&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_facebook.gif) no-repeat'},
						'events': {'click': this.end.bind(this) }
					}).setHTML('Facebook')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=twitter&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_twitter.gif) no-repeat'},
						'events': {'click': this.end.bind(this) }
					}).setHTML('Twitter')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=delicious&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_delicious.gif) no-repeat'},
						'events': {'click': this.end.bind(this) }
					}).setHTML('del.icio.us')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=digg&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_digg.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Digg')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=furl&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_furl.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Furl')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=netscape&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_netscape.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Netscape')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=yahoo&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_yahoo_myweb.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Yahoo! My Web')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=stumbleupon&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_stumbleupon.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('StumbleUpon')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=googlebookmarks&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_google_bmarks.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Google Bookmarks')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=technorati&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_technorati.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Technorati')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=blinklist&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_blinklist.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('BlinkList')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=newsvine&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_newsvine.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Newsvine')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=reddit&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_reddit.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('reddit')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=windowslive&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_windows_live.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Windows Live')
				),
				new Element('li').adopt(
					new Element('a',{
						'href': this.ajaxURL + '?service=tailrank&url='+this.fields[this.active].link+'&title='+this.fields[this.active].title,
						'target': '_blank',
						'styles': {'background': 'transparent url('+this.options.baseURL+'/images/share_tailrank.gif) no-repeat'},
						'events': {'click': this.end.bind(this)}
					}).setHTML('Tailrank')
				)
			])// </ul.social
		];
		this.bodydivs.each(function(el, i){
			if (i == this.options.active_tab)
				el.setStyle('display', 'block');
			else el.setStyle('display', 'none');
			el.inject(this.body);
		}.bind(this));

		// add google tracking
		this.bodydivs[1].getElements('a').each(function(el){
			el.addEvent('click', function(){
				if ( $chk( window[ '_gaq' ] ) ) {
					_gaq.push( [ '_trackEvent', 'sharethis', 'click', el.innerHTML.replace( /[^a-zA-Z0-9]/g, '' ) ] );
					_gaq.push( [ 'glg._trackEvent', 'sharethis', 'click', el.innerHTML.replace( /[^a-zA-Z0-9]/g, '' ) ] );
				}
			});
		})
	},

	reloadCAPTCHA: function(){
		this.captcha.value = '';
		this.captchaIMG.setProperty('src', this.options.baseURL+'/images/captcha.php?' + (new Date()).getTime());
	},

	sendEmail: function(){
		this.bodydivs[0].setStyle('opacity','0.5');
		var str = new Array();
		var query = {
			to: {name: 'To Address', value: this.toAddress.value},
			name: {name: 'Your Name', value: this.senderName.value},
			from: {name: 'Your Email Address', value: this.senderAddress.value},
			url: {name: 'URL', value: this.fields[this.active].link},
			subject: {name: 'Subject', value: this.subject.value},
			message: {name: 'Message', value: this.message.value},
			captcha: {name: 'Image Key', value: this.captcha.value}
		}
		for(var i in query) if(query[i].value.trim() == '') { this.showError(query[i].name); return; }
		for(var name in query) str.push(name+'='+encodeURIComponent(query[name].value));
		str = str.join('&');
		new Ajax(this.ajaxURL, {
			method: 'post',
			data: 'ax=send&'+str,
			onComplete: function(response){
				this.emailSent(response);
			}.bind(this)
		}).request();
	},

	showError: function(desc){
		this.bodydivs[0].setStyle('opacity','1');
		this.reloadCAPTCHA();
		if(this.alert_msg) { this.alert_msg.remove(); this.alert_msg=false; }
		this.alert_msg = new Element('p',{'class':'alert_msg'}).setHTML(desc + ' is missing or invalid').injectTop(this.body);
	},

	emailSent: function(response){
		if(response == 'Email Sent') {
			if(this.alert_msg) { this.alert_msg.remove(); this.alert_msg=false; }
			this.bodydivs[0].setStyle('opacity','1');
			this.alert_msg = new Element('p',{'class':'alert_msg'}).setHTML(response).injectTop(this.body);

			//Empty Input Fields
			this.toAddress.value = '';
			this.reloadCAPTCHA();
			var remove = (function(){this.alert_msg.remove();this.alert_msg=false;}.bind(this)).delay(5000);
		} else this.showError(response);
	},

	activeTab: function(id){
		for(var i=0; i<this.bodydivs.length; i++){
			if(i==id) {
				this.tablinks[i].addClass('selected');
				this.bodydivs[i].setStyle('display','block');
			}	else {
				if(this.tablinks[i]) this.tablinks[i].removeClass('selected');
				this.bodydivs[i].setStyle('display','none');
			}
		}
	},

	position: function(){
		var pos = this.fields[this.active].element.getPosition();
		this.sharebox.setStyles({
			'left': pos.x + this.options.offsets.x,
			'top': pos.y + this.options.offsets.y
		});
	},

	start: function(id){
		if(this.active!==false && this.active==id) { this.end(); return; }
		else this.active = id;

		this.build();
		this.position();
		this.sharebox.setStyle('opacity','0');
		if (this.options.timeout) this.timer = this.end.delay(this.options.timeout, this);
		this.fireEvent('onShow', [this.sharebox]);
	},

	end: function(){
		this.alert_msg=false;
		this.active = false;
		$clear(this.timer);
		this.fireEvent('onHide', [this.sharebox]);
		for(var i=0; i<this.bodydivs.length; i++) {
			this.bodydivs[i].removeProperty('style');
			if(window.webkit) this.bodydivs[i].setStyle('visibility','hidden');
		}
	}
});

ShareThis.implement(new Events, new Options);
