/**
 * @namespace Holds general multiven functionality
 */
var Multiven = {
	
	quoteBucket: new Array(),
	
	/**
	 * Scans the page for links with certain class names, and adds onclick actions to them
	 */
	init: function() {
		BODY = $$('body').first();
		
		// add onclick to flyover links
		var openFlyover = $A( $$('.openFlyover') );
		openFlyover.each( function(theLink) {
			theLink.onclick = function() {
				Multiven.openFlyover(theLink.href);
				return false;
			}
		} );

		// add onclick to flyover links
		var closeFlyover = $A( $$('.closeFlyover') );
		closeFlyover.each( function(theLink) {
			theLink.onclick = function() {
				Multiven.closeFlyover();
				return false;
			}
		} );

		// add onclick to bubble links
		var showBubble = $A( $$('.showBubble') );
		showBubble.each( function(theLink) {
			theLink.onclick = function() {
				Multiven.showBubble(this);
				return false;
			}
		} );

		// add onclick to bubble links
		var hideBubble = $A( $$('.hideBubble') );
		hideBubble.each( function(theLink) {
			theLink.onclick = function() {
				Multiven.hideBubble();
				return false;
			}
		} );
		
		this.setupDefaultTexts();
		this.preloadFlyover();
	},
	
	
	/**
	 * Setup default form values
	 */
	setupDefaultTexts: function() {
		$$('input.default_text', 'textarea.default_text').each(function(input) {
			var text = $F(input);
			Event.observe(input, 'focus', function() {
				var f = $(this);
				if (f.getValue() == text) f.setValue('');
			});
			Event.observe(input, 'blur', function() {
				var f = $(this);
				if (f.getValue() == '') f.setValue(text);
			});
			input.removeClassName('default_text');
		});
	},
	
	
	/**
	 * preloads a flyover, if present
	 */
	preloadFlyover: function() {
		var flyover = $('flyoverwrap');
		if (flyover != null) {
			flyover.show();
		}
	},
	
	
	/**
	 * open a flyover. hides all visible bubbles and flyovers first
	 */
	openFlyover: function(theHref) {
		// hide bubbles
		this.hideBubble();
		
		new Ajax.Request(theHref, {
			method: 'get',
			evalScripts: true,
			onComplete: function(transport) {
				Multiven.closeFlyover();
				BODY.insert(transport.responseText);
				Multiven.init();
			}
		});
	},
	
	
	/**
	 * Close a flyover
	 */
	closeFlyover: function() {
		var flyover = $('flyoverwrap');
		if (flyover != null) {
			flyover.remove();
		}
	}
};


/**
 * show  bubble
 */
Multiven.showBubble = function(theLink) {
	
	new Ajax.Request(theLink.href, {
		onSuccess: function() {
			$('popoverWrap').remove();
		},
		onComplete: function(transport) {
			$('bd').insert(transport.responseText);
			var flyover = $('popoverWrap');
			flyover.clonePosition(theLink, {
				setHeight: false,
				setWidth: false,
				offsetLeft: 30,
				offsetTop: (flyover.getHeight() - 12) * -1
			});
			Effect.Appear(flyover, {duration: 0.3});
			Multiven.init();
		}
	});
}


/**
 * hide a bubble
 */
Multiven.hideBubble = function() {
	
	var flyover = $('popoverWrap');
	if ( flyover ) {
		new Effect.Fade(flyover, {
			afterFinish: function(obj) { obj.element.remove(); },
			duration: 0.3
		});
	}
}


/**
 * show the Partner or Customer login choice
 */
Multiven.showLoginChoice = function(theLink) {
	$('loginChoice').clonePosition(theLink, {
		setHeight: false, 
		setWidth: false,
		offsetTop: theLink.offsetHeight
	});
	Effect.toggle('loginChoice','blind',{duration: 0.2});
}


/**
 * partner login
 */
Multiven.login = function() {
	$('loginForm').request({
		onComplete: function(transport,json) {
			if (json && json.status == 'OK')
				// Multiven.openFlyover('partner_news');
				window.location.href = 'partners?content=partner_home';
			else
				// Multiven.openFlyover('login_failed');
				window.location.href = 'partners?content=login_failed';
		}
	});
	// $('loginForm').submit();
}


/**
 * submits the contact form
 */
Multiven.submitContactForm = function() {
	$('contactForm').request({
		onComplete: function(transport,json) {
			if (json && json.status == 'OK')
				Multiven.openFlyover('contact_success');
			else
				Multiven.openFlyover('contact_failed');
		}
	});
}


/**
 * submits the mysolvr form under support
 */
Multiven.submitMysolvrForm = function(theLink) {
	var theForm = $('mysolvrForm');
	var query_string = theForm.serialize();
	theLink.href += '?' + query_string;
	return true;
}


/**
 * submits the school program form
 */
Multiven.submitSchoolForm = function(theLink) {
	var form = $(theLink).up('form');
	var invalid = false;
	var check_fields = $w("School_Name City Address State Country School_Head School_Head_Email School_Head_Phone School_Website");
	
	form.getInputs().each(function(element) {
		if (check_fields.include(element.name) && element.getValue().blank())
			invalid = true;
	});
	if (invalid) {
		this.showFormError(form, 'Please complete the form first.');
		return false;
	}
	
	form.request({
		onComplete: function(transport) {
			var json = transport.headerJSON;
			if (json.status == 'OK') {
				Multiven.openFlyover('school_success');
			}
			else if (json.status == 'CAPTCHA_FAILED') {
				Multiven.showFormError(form, 'Image recognition test failed. Please reload and try again.');
			}
			else {
				Multiven.openFlyover('school_failed');
			}
		}
	});
}


Multiven.showFormError = function(form, error) {
	var error_id = 'form-error';
	if ($(error_id) == null) {
		var error = '<div id="'+error_id+'"><p style="color: red; font-weight: bold;">'+error+'</p></div>';
		form.insert({top: error});
		new Effect.SlideUp(error_id, {
			delay: 5,
			afterFinish: function(obj) { obj.element.remove(); }
		});
	}
}


/**
 * observe the pricing form for changes and and make an ajax call to get the new value
 */
Multiven.observePricingForm = function(form, value) {
	form.request({
		onComplete: function(transport, json) {
			$('search_results').update(transport.responseText);
		}
	});
}


/**
 * add an item to the bucket
 */
Multiven.addToBucket = function(theLink, theItem) {
	
	// check if the item is already in there
	var item = Multiven.quoteBucket.find(function(item) {
		return (item.id == theItem.id && item.service == theItem.service);
	});
	
	if (item) {
		item.amount++;
	} else {
		theItem.pos = Multiven.quoteBucket.length;
		Multiven.quoteBucket.push(theItem);
	}

	Multiven.updateBucket();
}


/**
 * remove an item from the bucket
 */
Multiven.removeFromBucket = function(pos) {
	
	// check if the item is already in there
	var item = Multiven.quoteBucket.find(function(item) {
		return (item.pos == pos);
	});
	
	if (item) {
		Multiven.quoteBucket = Multiven.quoteBucket.without(item);
	}

	Multiven.updateBucket();
}


/**
 * show an inline editor for the table
 */
Multiven.showAmountEdit = function(theCell, pos) {
	
	// find the item
	var item = Multiven.quoteBucket.find(function(item) {
		return (item.pos == pos);
	});
	$(theCell).update('<input type="text" name="'+item.pos+'" value="'+item.amount+'" size="2" onblur="Multiven.updateAmount(this);" />');
	theCell.onclick = null;
}


/**
 * update the amount of an item in the bucket
 */
Multiven.updateAmount = function(theInput) {
	
	// get pos from input name
	var pos = theInput.name;
	
	// find the item
	var item = Multiven.quoteBucket.find(function(item) {
		return (item.pos == pos);
	});
	item.amount = theInput.value;
	
	Multiven.updateBucket();
}


/**
 * render a table with the bucket content
 */
Multiven.updateBucket = function() {
	
	var html = '';
	if (Multiven.quoteBucket.length > 0) {
		var total		= 0;
		var form_fields	= '';
		html	= "<table>\n<tr><th>&nbsp;</th><th>Product</th><th>Service</th><th>Unit Price</th><th align=\"right\">Total</th><th>&nbsp;</th></tr>\n";
		Multiven.quoteBucket.each(function(item) {
			html	+= '<tr><td onclick="Multiven.showAmountEdit(this,'+item.pos+');" title="Click to change the amount">'+item.amount+'</td>';
			html	+= '<td>'+item.name+'</td><td>'+item.service_text+'</td>';
			html	+= '<td align="right" class="amount">$ '+item.price+'</td><td align="right" class="amount">$ '+item.price*item.amount+'</td>';
			html	+= '<td><a href="#" onclick="Multiven.removeFromBucket('+item.pos+'); return false;" title="Click to remove this item">X</a></td></tr>';
			total	+= item.price * item.amount;
			form_fields	+= '<input type="hidden" name="prod['+item.pos+'][id]" value="'+item.id+'" />';
			form_fields	+= '<input type="hidden" name="prod['+item.pos+'][service]" value="'+item.service+'" />';
			form_fields	+= '<input type="hidden" name="prod['+item.pos+'][amount]" value="'+item.amount+'" />';
		});
		html += '<tr><td colspan="4">&nbsp;</td><td class="totalAmount">$ '+total+'</td><td>&nbsp;</td></tr>';
		html += "</table>\n";
		html += form_fields;
		html += '<a href="#" onclick="$(\'pricing_form\').action=\'do_partner_pricing.php?csv=1\'; $(\'pricing_form\').submit(); return false;" \
			title="Click to download your selection as a CSV file">Download CSV</a>';
	}
	
	$('quote_bucket').update(html);
}


/**
 * change nms info message in the partner tool
 */
Multiven.change_nms_info = function(select) {
	var value	= $F(select);
	var match	= /^nms_(.+)$/.exec(value);
	var sla		= match[1];
	
	var message;
	
	if (sla == '8x5x4' || sla == '24x7x4' || sla == '24x7x2') {
		message = 'Please also contact your Multiven account representative prior to sending out any quotes for 4 hour or 2 hour SLAs, to confirm availability.';
	}
	else {
		message = 'Please contact your Multiven account representative for 24x7xCPS NMS pricing.';
	}

	$('nms_info').update(message);
}


var ShareBox = {
	show: function(theLink) {
		
		var html =
		'<div id="popoverWrap" style="display: none; position: absolute; z-index: 1000;">' +
		'<div id="popoverFront" class="small">' +
			'<div class="popoverTL"></div>' +
			'<div class="popoverTR"><div class="closeBtn"><a href="#" class="hideBubble" onclick="ShareBox.hide(); return false;"><img src="images/close-btn.png" alt="X" /></a></div></div>' +
			'<div class="popoverMiddle-top"><div class="popoverMiddleInside"></div></div>' +
				'<div class="popoverLeft">' +
				'<div class="popoverRight">' +
					'<div class="popoverContentwrap clearfix">' +
					'<div class="popoverContent">' +
						'<div id="popnav" class="clearfix">' +	
						'<ul>' +
							'<li><a class="active shareLink" href="#" onclick="ShareBox.toggleGroup(this,\'share\'); return false;" name="social">Share</a></li>' +
							'<li><a class="shareLink" href="#" onclick="ShareBox.toggleGroup(this,\'share\'); return false;" name="email">Email</a></li>' +
						'</ul>' +
						'</div>' +
						// first tab starts here
						'<div class="clearfix shareContent" id="shareContent:social">' +
							'<div class="box-left" style="width: 50%;">' +
								'<ul class="shareItem">' +
									'<li><a target="_blank" href="http://del.icio.us/post?url='+theLink.href+'&amp;title='+theLink.title+'"><img src="images/icons/delicious.png" align="top" />&nbsp;&nbsp;Del.icio.us</a></li>' +
									'<li><a target="_blank" href="http://digg.com/submit?phase=2&url='+theLink.href+'&amp;title='+theLink.title+'"><img src="images/icons/digg.png" align="top" />&nbsp;&nbsp;Digg</a></li>' +
									'<li><a target="_blank" href="http://www.stumbleupon.com/submit?url='+theLink.href+'&amp;title='+theLink.title+'"><img src="images/icons/su.png" align="top" />&nbsp;&nbsp;StumbleUpon</a></li>' +
									'<li><a target="_blank" href="http://technorati.com/faves?add='+theLink.href+'"><img src="images/icons/technorati.png" align="top" />&nbsp;&nbsp;Technorati</a></li>' +
									'<li><a target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&bkmk='+theLink.href+'&amp;title='+theLink.title+'"><img src="images/icons/goog.png" align="top" />&nbsp;&nbsp;Google</a></li>' +
								'</ul>' +
							'</div>' +
							'<div class="box-right" style="50%;">' +
								'<ul class="shareItem">' +
									'<li><a target="_blank" href="http://www.newsvine.com/_tools/seed&save?u='+theLink.href+'&amp;h='+theLink.title+'"><img src="images/icons/newsvine.png" align="top" />&nbsp;&nbsp;Newsvine</a></li>' +
									'<li><a target="_blank" href="http://reddit.com/submit?url='+theLink.href+'&amp;title='+theLink.title+'"><img src="images/icons/reddit.gif" align="top" />&nbsp;&nbsp;Reddit</a></li>' +
									'<li><a target="_blank" href="http://www.facebook.com/sharer.php?u='+theLink.href+'&amp;t='+theLink.title+'"><img src="images/icons/facebook.gif" align="top" />&nbsp;&nbsp;Facebook</a></li>' +
									'<li><a target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;mkt=en-us&amp;url='+theLink.href+'&amp;title='+theLink.title+'&amp;top=1"><img src="images/icons/live.gif" align="top" />&nbsp;&nbsp;Windows live</a></li>' +
									'<li><a target="_blank" href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u='+theLink.href+'&amp;t='+theLink.title+'"><img src="images/icons/yahoo-myweb.png" align="top" />&nbsp;&nbsp;Yahoo MyWeb</a></li>' +
								'</ul>' +
							'</div>' +
						'</div>' +
						// second tab starts here
						'<div class="clearfix shareContent" id="shareContent:email" style="display: none;">' +
						'<form id="shareForm" class="formBox" action="do_share_email.php" method="post">' +
							'<input type="hidden" name="url" value="'+theLink.href+'" />' +
							'<p><label>To Email:</label> <input type="text" class="inputbox" name="to_email" /></p>' +
							'<p><label>From Email:</label> <input type="text" class="inputbox" name="from_email" /></p>' +
							'<p><label>Your Name:</label> <input type="text" class="inputbox" name="from_name" /></p>' +
							'<p><label>Message:</label><textarea class="inputbox" name="message">Take a look at this...\n\nTitle: '+theLink.title+'\nURL: '+theLink.href+'</textarea></p>' +
						'</form>' +
						'<div id="form-buttonset" class="clearfix">' +
							'<div style="margin:5px auto; width: 150px;">' +
							'<div class="solvr-box-1" style="line-height:22px; margin: 0 1px;">' +
							'<a class="button" href="#" onclick="ShareBox.submitForm(); return false;"><span><span>Send</span></span></a>' +
							'</div>' +
							'<div class="solvr-box-2" style="line-height:22px; margin: 0 1px;">' +
							'<a class="button" href="#" onclick="ShareBox.hide(); return false;"><span><span>Cancel</span></span></a>' +
							'</div>' +
							'</div>' +
						'</div>' +
						'</div>' +
						// second tab ends here
					'</div>' +
					'</div>' +
					'<!-- END: CONTENT -->' +
				'</div>' +
				'</div>' +
			'<div class="popoverBR"></div>' +
			'<div class="popoverBL"></div>' +
			'<div class="popoverMiddle-bottom"><div class="popoverBottomInside"></div></div>' +
		'</div>' +
		'</div>';
		$('bd').insert({top: html});

		this.box	= $('popoverWrap');
		this.link	= theLink;
		this.position();
		Effect.Appear(this.box, {duration: 0.3});
	},
	
	position: function() {
		var box = this.box;
		var link = this.link;
		box.clonePosition(link, {
			setHeight: false, 
			setWidth: false, 
			offsetTop: (box.getHeight() - 5) * -1,
			offsetLeft: -5
		});
	},
	
	hide: function() {
		if (this.box) {
			Effect.Fade(this.box, {
				duration: 0.3,
				afterFinish: function(obj) { obj.element.remove(); }
			});
		}
	},
	
	toggleGroup: function(theLink, group) {

		// close all opened bubbles
		var newBubble = $(group + 'Content:' + theLink.name);
		var currentBubble = $$('.'+group+'Content').find(function(bubble) {
			return bubble.visible();
		});
		var currentHeight	= (currentBubble.storedHeight || currentBubble.getHeight());
		var newHeight		= (newBubble.storedHeight || newBubble.getHeight());
		currentBubble.storedHeight = currentHeight;
		newBubble.storedHeight = newHeight;
		
		var moveBy = currentHeight - newHeight;
		var scalePercent = (newHeight / currentHeight) * 100;
		
		new Effect.Fade(currentBubble, {queue: 'end', duration: 0.2});
		new Effect.Parallel([
			new Effect.Move('popoverWrap', {mode: 'relative', y: moveBy, sync: true}),
			// new Effect.Scale('popoverWrap', scalePercent, {scaleX: false, sync: true})
		],
		{
			duration: 0.2,
			afterFinish: function(obj) {
				ShareBox.position();
			}
		});
		new Effect.Appear(newBubble, {queue: 'end', duration: 0.2});


		if ( theLink.hasClassName('active') ) {
			theLink.removeClassName('active');
		} else {
			// make all bubble links inactive
			$$('.'+group+'Link').each(function(link) {
				link.removeClassName('active');
			});
			theLink.addClassName('active');
		}
	},
	
	bookmark: function(theLink) {
		// firefox
		if (window.sidebar) {
			window.sidebar.addPanel(theLink.title, theLink.href, "");
			return false;
		}
		// opera
		else if (window.opera && window.print) {
			theLink.setAttribute('rel','sidebar');
			return true;
		}
		// internet explorer
		else if (document.all) {
			window.external.AddFavorite(theLink.href, theLink.title);
			return false;
		}
	},
	
	submitForm: function() {
		$('shareForm').request({
			onComplete: function(transport) {
				var json = transport.responseJSON;
				if (json && json.status == 'OK') {
					ShareBox.showFlashMessage('Your email has been sent', 'info', 'shareForm');
					setTimeout("ShareBox.hide()", 5000);
				}	
				else {
					ShareBox.showFlashMessage('Oops! Try again.', 'error', 'shareForm');
				}
			}
		});
	},
	
	showFlashMessage: function(message, type, container) {

		// set default type and container
		type = typeof(type) != 'undefined' ? type : 'info';
		container = typeof(container) != 'undefined' ? container : 'bd';

		// do nothing if the type is not known
		if (type != 'info' && type != 'notice' && type != 'error')
			return;

		// set the colors
		// var colors = {
		//       error:	{startcolor: '#FDEAED', endcolor: '#FFFFFF'},
		//       notice:	{startcolor: '#FFFFE6', endcolor: '#FFFFFF'},
		//       info:		{startcolor: '#EBFFC2', endcolor: '#FFFFFF'}
		//     };

	    var html = '<div id="flash-'+type+'"><h4>'+message+'</h4></div>';

		// find the container
		var theContainer = $(container);
		if (theContainer == null)
			theContainer = $('bd');
		theContainer.insert({top: html});

		var flash = $('flash-'+type);
		new Effect.Appear(flash);
		new Effect.Fade(flash, {delay: 7});
		new Effect.BlindUp(flash, {
			delay: 7,
			afterFinish: function(obj) { flash.remove(); }
		});	
	}
};

var BODY;
// add the init event to window.onload
Event.observe(window, 'load', Multiven.init.bind(Multiven));
