/**
 * ShareIt
 * Bookmarking and sharing widget
 *
 * @author Kaitlyn McLachlan <kaitlyn@clearskymedia.ca>
 * @copyright Copyright 2009, Clear Sky Media Inc.
 */

var ShareIt = {
	initialized : false,

	active : null,
	current_page : null,

	config : {
		path : '/csm/shareit',
		overlay : 'dark',
		closetext : 'X'
	},

	default_params : {
		link : window.location.href,
		title : document.title
		
	},
	params : null,

	init : function(options) {
		options = options || {};

		$(document).ready(function() {
			$('<div id="shareit-overlay" class="shareit-overlay-' + ShareIt.config.overlay + '"style="display:none"></div>').appendTo('body').click(function() {
				ShareIt.close();
			});

			if ($.browser.msie) {
				$('#shareit-overlay').css({
					position : 'absolute',
					width : $(window).width(),
					height : $(window).height()
				});
			}
		});

		for (var i in options) {
			if (options[i]) {
				this.config[i] = options[i];
			}
		}

		this.initialized = true;
	},

	plugins : {
		pluginlist : [],

		addService : function(name, icon_offset, url) {
			this.pluginlist.push([name, icon_offset, 'service', url]);
		},

		addPage : function(name, icon_offset, pageid, pagetitle) {
			this.pluginlist.push([name, icon_offset, 'page', pageid, pagetitle]);
		},

		addPlugin : function(name, icon_offset, function_name) {
			this.pluginlist.push([name, icon_offset, 'plugin', function_name]);
		}
	},

	goToService : function(url) {
		url = url.replace('__URL__', encodeURIComponent(this.params.link)).replace('__TITLE__', encodeURIComponent(this.params.title));

		window.open(url, 'shareit', 'width=800,height=600,top=0,left=0,toolbar=1,menubar=1,scrollbars=1,status=1');
		this.close();

		return false;
	},

	show : function(obj, params) {
		if (!this.initialized) { this.init(); }

		params = params || {};
		params = $.extend(this.config, this.default_params, params);

		$('#shareit-overlay').show();

		var shareobj = $('#shareit-dialog');

		if (shareobj.length != 1) {
			this.drawShareIt(obj, params);
			shareobj = $('#shareit-dialog');
		}
		
		if (!this.loaded_nospam) {
			$.ajax({
				url : this.config.path + '/email.php',
				cache : false,
				type : 'GET',
				data : 'do=load_nospam',
				dataType : 'json',
				success : function(response) {
					ShareIt.loaded_nospam = true;
					$('#frmShareItEmail').append(response.field_tstamp).append(response.field_hash);
				},
				error : function(request, status, error) {
					ShareIt.loaded_nospam = true;
					$('#shareit-dialog a[rel="shareit-email"]').hide();
				}
			});
		}

		this.active = shareobj;
		this.params = params;

		this.switchPage('plugins');
		
		return false;
	},

	updatePos : function() {
		var objwidth = this.active.outerWidth();
		var objheight = this.active.outerHeight();
		
		var scrolltop = 0;
		var top = '50%';
		
		if ($.browser.msie) {
			scrolltop = $(document).scrollTop();
			$('#shareit-overlay').css('top', scrolltop);
			top = scrolltop + parseInt($(window).height() / 2) + 'px'
		}

		this.active.show().css({
			top : top,
			left : '50%',
			marginLeft : '-' + parseInt(objwidth / 2) + 'px',
			marginTop : '-' + parseInt(objheight / 2) + 'px'
		});
	},

	drawShareIt : function(obj, params) {
		var self = this;

		$(document).ready(function() {
            var widget = [];
            var i = 0;
            
			widget[i++] = '<div id="shareit-titlebar"><div id="shareit-close"><a href="#" onclick="return ShareIt.close()">' + ShareIt.config.closetext + '</a></div><span id="shareit-titletext">Bookmark &amp; Share</span></div>';
            widget[i++] = '<div class="shareit-msgbox error-msg" style="display:none"></div><div class="shareit-msgbox success-msg" style="display:none"></div>';

			// Create Plugins page
			widget[i++] = '<div id="shareit-page-plugins" class="shareit-page clearfix" style="display:none">';
				var numPlugins = self.plugins.pluginlist.length;
				if (numPlugins > 3) {
					widget[i++] = '<div id="shareit-heading">Most Popular Services</div>';
				}
				for (x = 0; x < numPlugins; x++) {
					if (self.plugins.pluginlist[x][2] == 'service') {
						widget[i++] = '<a class="shareit-plugin" target="_blank" href="#" onclick="return ShareIt.goToService(\'' + self.plugins.pluginlist[x][3] + '\')"><span style="background-position:0 ' + (self.plugins.pluginlist[x][1] * -16) + 'px">' + self.plugins.pluginlist[x][0] + '</span></a>';
					} else if (self.plugins.pluginlist[x][2] == 'page' ){
						widget[i++] = '<a class="shareit-plugin" target="_blank" href="#" rel="shareit-' + self.plugins.pluginlist[x][3] + '" onclick="return ShareIt.switchPage(\'' + self.plugins.pluginlist[x][3] + '\', \'' + self.plugins.pluginlist[x][4] + '\')"><span style="background-position:0 ' + (self.plugins.pluginlist[x][1] * -16) + 'px">' + self.plugins.pluginlist[x][0] + '</span></a>';
					} else {
						widget[i++] = '<a class="shareit-plugin" target="_blank" href="#" onclick="return ' + self.plugins.pluginlist[x][3] + '()"><span style="background-position:0 ' + (self.plugins.pluginlist[x][1] * -16) + 'px">' + self.plugins.pluginlist[x][0] + '</span></a>';
					}

					if (numPlugins > 3 && x == 2) {
						widget[i++] = '<div style="clear:both">&nbsp;</div>';
					}
				}
            widget[i++] = '</div>';

			// Create email friend page
			widget[i++] = '<div id="shareit-page-email" class="shareit-page clearfix" style="display:none"><form id="frmShareItEmail" action="' + ShareIt.config.path + '/email.php" method="post" onsubmit="return ShareIt.sendEmail(this)"><input type="text" name="name" id="shareit-namefield" />';
				widget[i++] = '<div class="clearfix"><div style="display:inline; float:left; width:160px"><label>From: <span>(your email address)</span></label><input type="text" name="from" size="25" class="textfield" value="' + (ShareIt.config.email_from || '') + '" /></div>';
				widget[i++] = '<div style="display:inline; float:right; width:160px; margin-left:10px"><label>To: <span>(their email address)</span></label><input type="text" name="to" size="25" class="textfield" /></div></div>';
				widget[i++] = '<label>Comments: <span>(optional)</span></label><textarea name="comments" cols="25" rows="4" class="textfield"></textarea><input type="submit" value="Send" class="button button-submit" /> <input type="button" value="Cancel" class="button" onclick="ShareIt.close()" />';
				widget[i++] = ' <img class="ajax" style="display:none" src="' + ShareIt.config.path + '/images/ajax.gif" width="16" height="11" alt="Please wait..." />';
				widget[i++] = '</form>';
			widget[i++] = '</div>';

			$('<div id="shareit-dialog">' + widget.join('') + '</div>').appendTo('body');
			
			$(document).keyup(function(e) {
				if (ShareIt.active && e.keyCode == 27) { // Close the ShareIt dialog on ESC key
					ShareIt.close();
				}
			});
			if ($.browser.msie) {
				$('#shareit-dialog').css('position', 'absolute');
				$(window).scroll(function() {
					if (self.active) {
						self.updatePos();
					}
				});
			}
		});
	},

	attachLink : function(obj, params) {
		var tmpobj = obj;
		var tmpparams = params;

		$(document).ready(function() {
			$('#' + tmpobj).click(function() {
				ShareIt.show(tmpobj, tmpparams);
				return false;
			});
		});
	},

	close : function() {
		if (this.active) {
			this.active.css({
				top : -1000,
				left : -1000
			});
		}

		$('#shareit-overlay').hide();

		this.active = null;

		$('#shareit-dialog').trigger('close');

		return false;
	},

	switchPage : function(page, title) {
		if (this.current_page) {
			$('#shareit-page-' + this.current_page).hide();
		} else if (this.current_page == page) {
			return false;
		}

		if (page == 'plugins') {
			title = 'Bookmark & Share';
		} else if (!title) {
			title = '&nbsp;';
		}

		$('#shareit-titletext').text(title);
		$('#shareit-page-' + page).show();
		$('.shareit-msgbox').hide();
		$('#shareit-dialog .error').removeClass('error');
		this.current_page = page;

		if ($.browser.msie) {
			$('#shareit-dialog').width($('#shareit-page-' + page).outerWidth());
		}
		
		this.updatePos();

		return false;
	},

	sendEmail : function(form) {
		form = $(form);

		form.find('.error').removeClass('error');

		if (!this.isValidEmail(form.find('input[name="from"]').val())) {
			this.showMessage('Please enter a valid email address', 'error');
			form.find('input[name="from"]').addClass('error');
			return false;
		} else if (!this.isValidEmail(form.find('input[name="to"]').val())) {
			this.showMessage('Please enter a valid email address', 'error');
			form.find('input[name="to"]').addClass('error');
			return false;
		}

		form.find('.ajax').show();
		$.ajax({
			type : 'POST',
			url : this.config.path + '/email.php',
			data : form.serialize() + '&' + $.param(ShareIt.params),
			success : function(response) {
				if (response == 'success') {
					ShareIt.active.find('.error-msg').hide();
					form.hide();
					ShareIt.active.find('.success-msg').html('Your messsage has been sent').show();

					$('#shareit-dialog').bind('close', function() {
						$('#shareit-page-email form').show().each(function() {
							this.reset();
						});
						$('#shareit-page-email .ajax').hide();
					});
					
					setTimeout(function() { ShareIt.close() }, 3000);
				} else {
					ShareIt.active.find('.error-msg').html(response).show();
					ShareIt.active.find('.ajax').hide();
				}
			},
			error : function(request, status, error) {

			}
		});

		return false;
	},

	isValidEmail : function(email) {
		if (/^[a-z0-9._%\-+]+@[a-z0-9.\-]+\.[a-z]{2,4}$/.test(email)) {
			return true;
		} else {
			return false;
		}
	},

	showMessage : function(msg, type) {
		if (!this.active) {
			return false;
		}

		if (type == 'error') {
			this.active.find('.error-msg').html(msg).show();
		} else {
			this.active.find('.success-msg').html(msg).show();
		}
	},

	addFav : function() {
		this.close();

		if (window.sidebar) { // Firefox
			window.sidebar.addPanel(this.params.title, this.params.link, "");
		} else if (document.all) { // IE
			window.external.AddFavorite(this.params.link, this.params.title);
		} else {
			alert('Use CTRL+D on your keyboard to bookmark this page');
		}

		return false;
	},

	print : function() {
		alert('Not yet implemented!');
		return false;
	}
};

ShareIt.plugins.addPage('Email', 9, 'email', 'Email a Friend');
ShareIt.plugins.addService('Facebook', 0, 'http://www.facebook.com/sharer.php?u=__URL__&t=__TITLE__');
ShareIt.plugins.addService('Twitter', 1, 'http://twitter.com/home/?status=__TITLE__%3A%20__URL__');
ShareIt.plugins.addService('Buzz', 11, 'http://www.google.com/buzz/post/?url=__URL__&title=__TITLE__');
ShareIt.plugins.addPlugin('Bookmark', 10, 'ShareIt.addFav');
ShareIt.plugins.addService('Delicious', 2, 'http://www.delicious.com/post/?url=__URL__&title=__TITLE__');
ShareIt.plugins.addService('Digg', 3, 'http://www.digg.com/submit/?url=__URL__&title=__TILE__');
ShareIt.plugins.addService('Google', 4, 'http://www.google.com/bookmarks/mark?op=add&title=__TITLE__&bkmk=__URL__');
ShareIt.plugins.addService('Live', 5, 'http://favorites.live.com/quickadd.aspx?url=__URL__&title=__TITLE__');
ShareIt.plugins.addService('MySpace', 6, 'http://www.myspace.com/Modules/PostTo/Pages/?t=__TITLE__&c=%20&u=__URL__&l=2');
ShareIt.plugins.addService('StumbleUpon', 7, 'http://www.stumbleupon.com/submit?url=__URL__&title=__TITLE__');
ShareIt.plugins.addService('Technorati', 8, 'http://technorati.com/faves?add=__URL__');
