/*jslint  browser: true, jquery: true, laxbreak: true */
/* global amplify debug; */

/* Declare a namespace for the App */
// var APP = window.APP || {};
// 
// APP.publish     = amplify.publish;
// APP.subscribe   = amplify.subscribe;
// APP.unsubscribe = amplify.unsubscribe;
// APP.request     = amplify.request;
// APP.store       = amplify.store;

jQuery.ajaxSetup({
	error: function(XMLHttpRequest, textStatus, errorThrown) {
		debug.groupCollapsed('Ajax Error', this.url, errorThrown, " - " + XMLHttpRequest.statusText + " (" + XMLHttpRequest.status + ")" );
		debug.log('$.ajax', this);
		debug.log('XMLHttpRequest', XMLHttpRequest);
		debug.log('status', XMLHttpRequest.statusText, XMLHttpRequest.status);
		debug.groupCollapsed('responseText');
		debug.dirxml(XMLHttpRequest.responseText);
		debug.groupEnd();
		debug.groupEnd();
	}
});

(function ($) {

	// Log all jQuery AJAX requests to Google Analytics
	$(document).ajaxSend(function(event, xhr, settings){
		window._gaq = window._gaq || [];
		window._gaq.push(['_trackEvent', 'ajax', 'request', 'url', settings.url]);
	});

}(jQuery));

if (jQuery && jQuery.easing && jQuery.easing.def) {
	jQuery.easing.def = 'easeOutQuart';
}

if (jQuery && jQuery.datepicker) {
	jQuery.datepicker.setDefaults({
		"dateFormat": 'yy-mm-dd'
		// , "showOn": 'both'
		// , "buttonImageOnly": true
		// , "buttonImage": 'calendar.gif' // '/images/misc/icon-calendar.gif'
		// , "buttonText": 'Calendar'
	});
}


/*!
 * jQuery isjQuery - v0.4 - 2/13/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Since every jQuery object has a .jquery property, it's usually safe to test
// the existence of that property. Of course, this only works as long as you
// know that any non-jQuery object you might be testing has no .jquery property.
// So.. what do you do when you need to test an external object whose properties
// you don't know?
//
// If you currently use instanceof, read this Ajaxian article:
// http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak
jQuery.isjQuery = function(obj) {
	return obj && obj.hasOwnProperty && obj instanceof jQuery;
};

// http://paulirish.com/2008/jquery-doonce-plugin-for-chaining-addicts/
jQuery.fn.doOnce = function(func) {
	if(this.length) { func.apply(this); }
	return this;
};

/*!
 * getUniqueClass - v1.1 - 2/13/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 */
jQuery.getUniqueClass = function() {
	var name, i = 0;
	while (jQuery('.' + (name = 'rb-' + (+new Date()) + (i++))).length) {
		// debug.log('taken.');
	}
	return name;
};

/**
 * list the event handler's of any event binded to any element
 *
 * // List all onclick handlers of all anchor elements:
 * $('a').debugListHandlers('onclick', console.info);
 *
 * // List all handlers for all events of all elements:
 * $('*').debugListHandlers('*', console.info);
 *
 * // Write a custom output function:
 * $('#whatever').debugListHandlers('click',function(element,data){
 *     $('body').prepend('<br />' + element.nodeName + ': <br /><pre>' + data + '<\/pre>');
 * });
 *
 * Note, this will only work if you've used jQuery's native event registration methods, e.g. $(elem).click() / $(elem).bind('click')
 *
 * @author James Padolsey
 * @link http://james.padolsey.com/javascript/debug-jquery-events-with-listhandlers/
 */
jQuery.fn.debugListHandlers = function(events, outputFunction) {
	return this.each(function(i) {
		var elem = this,
			dEvents = $(this).data('events');
		if (!dEvents) {
			return;
		}
		$.each(dEvents, function(name, handler) {
			if ((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',', '|').replace(/^on/i, '')) + ')$', 'i')).test(name)) {
				$.each(handler, function(i, handler) {
					outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler);
				});
			}
		});
	});
};

// http://happygiraffe.net/blog/2007/09/26/jquery-logging/
jQuery.fn.log = function(msg) {
	// debug.log('prev', this.prevObject);
	debug.group(this.selector + ' ['+this.length+' matches]');
	if (msg) debug.log(msg);
	debug.log(this);
	if(this.length > 0) {
		debug.log(this.get(0));
	}
	debug.groupEnd();
	return this;
};

/*!
* jQuery queueFn - v0.7 - 9/05/2010
* http://benalman.com/projects/jquery-misc-plugins/
*/
(function($) {
	$.fn.queueFn = function(fn) {
		var i, that, args = Array.prototype.slice.call(arguments, 1);

		if (typeof fn === 'boolean') {
			if (fn) {
				that = this;
				i = this.length;
			}
			fn = args.shift();
		}

		fn = $.isFunction(fn) ? fn : $.fn[fn];

		return this.queue(function() {
			if(! --i) {
				fn.apply(that || this, args);
			}
			$.dequeue(this);
		});
	};
}(jQuery));

/*!
* jQuery scrollbarWidth - v0.2 - 2/11/2009
* http://benalman.com/projects/jquery-misc-plugins/
*/
(function($, undefined, width) {
	$.scrollbarWidth = function() {
		var parent, child;
		if (width === undefined) {
			parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
			child = parent.children();
			width = child.innerWidth() - child.height(99).innerWidth();
			parent.remove();
		}
		return width;
	};
}(jQuery));

/*!
 * jQuery serializeObject - v0.2 - 1/20/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 */
// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.
(function($, undefined) {
	$.fn.serializeObject = function() {
		var obj = {};
		$.each(this.serializeArray(), function(i, o) {
			var n = o.name,
				v = o.value;
			obj[n] = obj[n] === undefined ? v : $.isArray(obj[n]) ? obj[n].concat(v) : [obj[n], v];
		});
		return obj;
	};
}(jQuery));

/*!
* jQuery viewportOffset - v0.3 - 2/3/2010
* http://benalman.com/projects/jquery-misc-plugins/
*/
// Like the built-in jQuery .offset() method, but calculates left and top from
// the element's position relative to the viewport, not the document.
(function($) {
	var win = $(window);

	$.fn.viewportOffset = function() {
		var offset = $(this).offset();

		return {
			left: offset.left - win.scrollLeft(),
			top: offset.top - win.scrollTop()
		};
	};

}(jQuery));

(function($) {

	jQuery.fn.freeze = function() {
		return this.each(function() {
			var elem = $(this);
			elem.data('preFreezeHeight', elem.css('height')).css('height', elem.height());
		});
	};

	jQuery.fn.unfreeze = function() {
		return this.each(function() {
			var elem = $(this);
			elem.css('height', elem.data('preFreezeHeight') || '');
		});
	};

}(jQuery));

/* Create a closure to maintain scope of the '$'
   and remain compatible with other frameworks.  */
(function($) {

	$(document).ready(function() {

		$('a[href="#"]').live('click', function(e) {
			e.preventDefault();
		});

		$('input').each(function() {
			var el = $(this),
				type = el.attr('type');

			if (type !== '') {
				el.addClass(type);
			}
		});

		jQuery.facebox.settings.loadingImage = '/images/jquery/loading.gif';
		jQuery.facebox.settings.closeImage = '/images/jquery/closelabel.png';
		$('a[rel*=facebox]').facebox();


		jQuery('[data-trigger-toggle]').live('click', function() {
			var selector = $(this).data('trigger-toggle');
			jQuery(selector).toggle();
		});

		/*
		$('.tabs').tabs();
		if ($.isFunction(jQuery.fn.button)) {
			var buttons = $('.btn, .button, button, input[type=button], input[type=submit]').button();
			buttons.filter('.preview').button("option", {
				icons: {
					primary: 'ui-icon-quicklook'
				}
			});

			buttons.filter('[data-ui-icon-primary]').each(function() {
				var iconSymbol = $(this).data('ui-icon-primary'),
					currentIcons = $(this).button("option", "icons");
				$(this).button("option", {
					icons: {
						primary: 'ui-icon-' + iconSymbol,
						secondary: currentIcons["secondary"]
					}
				});
			});
			if ($.isFunction(jQuery.fn.buttonset)) {
				$('.button-toggle-set').buttonset();
			}
		}
		*/

		if ($.isFunction(jQuery.fn.datepicker)) {
			$('input[type="date"], .datepicker').datepicker();
		}

	});

	$.simpleWidget('rbTabs', {
		options: {
			
		},
		_create: function() {
			var widget = this,
				initial_state;
			this.element.addClass('rb-tabs');

			if(!this.options.tabset_name) {
				this.options.tabset_name = this.element.attr( 'id' ) || 'tabs-' + ($('.tabs').index(this.element) + 1);
			}

			this.nodes = {
				"tabset": this.element.find('.tab-control'),
				"tabs": this.element.find('.tab-control li'),
				"panels": this.element.find('.panels')
			};

			this.element.delegate(".tab-control a", "click", function(e) {
				e.preventDefault();
				var $this = $(this),
					newTabId = $this.attr('href').replace(/#/, '');
				widget.select(newTabId);
			});

			initial_state = $.bbq.getState( this.options.tabset_name );
			if (initial_state) {
				widget.select(initial_state);
			}

		},
		destroy: function() {
			this.element.removeClass('ui-messages-list');
		},
		select: function(tabId) {
			var newTab = this.nodes.tabset.find('a[href="#' + tabId + '"]').parents('li:first'),
				newTabPanel = this.nodes.panels.find('#' + tabId),
				state = {};

			this.nodes.tabset.find('a').not(newTab).parents('li').removeClass('current');
			newTab.addClass('current');

			this.nodes.panels.find('.panel').not(newTabPanel).removeClass('current');
			newTabPanel.addClass('current');

			state[this.options.tabset_name] = tabId;
			$.bbq.pushState(state);
		}
	});

	$(document).ready(function() {

		$('.module.tabs').rbTabs();

	});


	$(document).ready(function() {
		$('#apply-form #apply-form-submit').live('click', function() {
			var applicationEl = $('#application');
			if (applicationEl.is(':visible') && applicationEl.val() !== '') {
				return true;
			}
			$('#apply-form-fields').slideDown('fast');
			applicationEl.focus();
			return false;
		});
	});



	$(document).ready(function() {
		$(".save-search-button").live('click', function(ev) {
			ev.preventDefault();
			var el = $(this);
			var url = el.attr("href");
			$.ajax({
				data: el.data('search'),
				dataType: 'json',
				timeout: 10000,
				type: 'GET',
				url: url,
				success: function(response, textStatus) {
					if (response.result === 'success') {
						var namer, btn, frm, searchId;
						searchId = response.data.saved_search.id;
						namer = $('<input/>', {
							"type": "text",
							"name": "search_name"
						});
						btn = $('<button/>', {
							"click": function(ev) {
								ev.preventDefault();
								$.ajax({
									data: {
										"id": searchId,
										"name": namer.val()
									},
									// dataType: 'json',
									timeout: 10000,
									type: 'POST',
									url: '/profile/rename_saved_search',
									success: function(response, textStatus) {
										$('.saved-search-namer').replaceWith(
											$('<div/>', {
												"class": "success message",
												"text": "Your Search was successfully named."
											})
										);
									},
									error: function(XMLHttpRequest, textStatus, errorThrown) {
									},
									complete: function(resp, abc) {
									}
								});
							}
						}).append("<span>Save Name</span>");

						frm = $('<div/>', {
							"class": "saved-search-namer"
						});
						$('.save-search-button:first').replaceWith(frm);
						frm.append(namer).append(btn);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					el.after('<span/>', {
						"class": "error",
						"text": "There was a problem saving the search. Please try again."
					});
				}
			});
		});
	});

	$(document).ready(function() {
		$(".save-internship-button").live('click', function(ev) {
			ev.preventDefault();
			var el = $(this);
			var url = el.attr("href");
			$.ajax({
				dataType: 'json',
				timeout: 10000,
				type: 'GET',
				url: url,
				success: function(response, textStatus) {
					if (response.result === 'success') {
						el.replaceWith(
							$('<div/>', {
								"class": "success message",
								"text": "This internship has been successfully saved to your dashboard."
							})
						);
					} else if (response.result === 'exists') {
						el.replaceWith(
							$('<div/>', {
								"class": "success message",
								"text": "This internship has already been saved to your dashboard."
							})
						);
					} else {
						el.replaceWith(
							$('<div/>', {
								"class": "error message",
								"text": "There was a problem saving the internship. Please try again later.",
								"style": "margin-top: 10px"
							})
						);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					el.replaceWith(
						$('<div/>', {
							"class": "error message",
							"text": "There was a problem saving the internship. Please try again later.",
							"style": "margin-top: 10px"
						})
					);
				}
			});
		});
	});

	$(document).ready(function() {
		$(".save-intern-button").live('click', function(ev) {
			ev.preventDefault();
			var el = $(this);
			var url = el.attr("href");
			$.ajax({
				dataType: 'json',
				timeout: 10000,
				type: 'GET',
				url: url,
				success: function(response, textStatus) {
					if (response.result === 'success') {
						$('p.options').after(
							$('<div/>', {
								"class": "success message",
								"text": "This intern has been successfully saved to your dashboard."
							})
						);
					} else if (response.result === 'exists') {
						$('p.options').after(
							$('<div/>', {
								"class": "success message",
								"text": "This intern has already been saved to your dashboard."
							})
						);
					} else {
						$('p.options').after(
							$('<div/>', {
								"class": "error message",
								"text": "There was a problem saving the intern. Please try again later.",
								"style": "margin-top: 10px"
							})
						);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					$('p.options').after(
						$('<div/>', {
							"class": "error message",
							"text": "There was a problem saving the intern. Please try again later.",
							"style": "margin-top: 10px"
						})
					);
				}
			});
		});
	});

	$(document).ready(function(){
		$('#slideout_form').submit(function() {
			// reset
			$('.details').html('<h3>The following fields must be corrected before your message is sent:</h3>');

			var errors = false;

			var message = $("#slideout_form #message").val();
			if (message === "") {
				$('.details').append('<div class="validation-error-detail">The Message field is required.</div>');
				$('#slideout_form #message-label').addClass('error');
				errors = true;
			}

			var emailAddress = $("#slideout_form #email-address").val();
			// var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			var re = /^(([^<>()\[\]\\.,;:\s@\"]+(\.[^<>()\[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			var validEmail = emailAddress.match(re);
			if (emailAddress === "") {
				$('.details').append('<div class="validation-error-detail">The Email address field is required.</div>');
				$('#slideout_form #email-address-label').addClass('error');
				errors = true;
			} else if (validEmail === null) {
				$('.details').append('<div class="validation-error-detail">The Email address is in an incorrect format.</div>');
				$('#slideout_form #email-address-label').addClass('error');
				errors = true;
			}

			// var image_verification = $("#slideout_form #image_verification").val();
			// if (image_verification === "") {
			// 	$('.details').append('<div class="validation-error-detail">The Image Verification field is required.</div>');
			// 	$('#slideout_form #image_verification-label').addClass('error');
			// 	errors = true;
			// }
			var verification = $("#slideout_form #verification").val();
			if (verification === "") {
				$('.details').append('<div class="validation-error-detail">The Verification field is required.</div>');
				$('#slideout_form #verification-label').addClass('error');
				errors = true;
			}

			if (errors) {
				$('.message').show();
				return false;
			} else {
				$('.message').hide();
			}

			var mode      = $("#slideout_form #mode").val();
			var isAjax    = $("#slideout_form #ajax").val();
			var page      = $("#slideout_form #page").val();

			var dataString = 'email-address=' + emailAddress + '&message='+ message + '&page=' + page + '&mode=' + mode + '&ajax=' + isAjax + '&verification=' + verification;
		    $.ajax({
				type: "POST",
				url: "/contact",
				data: dataString,
				success: function(html) {
					if (html == 'captcha_error') {
						$('.details').html('<h3>The following fields must be corrected before your message is sent:</h3>');
						$('.details').append('<div class="validation-error-detail">The Verification field must equal the correct sum.</div>');
						$('.message').show();
					} else {
						$('#slideout_form').fadeOut(500, function(){
							$('.slideout_success').fadeIn(500);
						});
					}
				}
		    });
			return false;
		});
	});

	$(document).ready(function() {
		if ($("input:radio[name=user]:checked").val() == 'employer') {
			$('.organization_row').show();
			$('.student_row').hide();
		} else {
			$('.organization_row').hide();
			$('.student_row').show();
		}

		$("input:radio[name=user]").live('click', function() {
		    if ($(this).val() == 'employer') {
				$('.organization_row').show();
				$('.student_row').hide();
			} else {
				$('.organization_row').hide();
				$('.student_row').show();
			}
		});

		$( "#organization_search" ).autocomplete({
			source: "/account/autocomplete",
			minLength: 3,
			select: function( event, ui ) {
				var organization_id = ui.item.id;
				var organization_name = ui.item.label;
				$('input[name="organization_id"]').val(organization_id);
				$('.org_type').hide();
			}
		});
		$('#organization_search').change(function(){
			$('input[name="organization_id"]').val("");
			$('.org_type').show();
		});
	});

	$(document).ready(function(){
		if ($('body').hasClass('ajax')) {
			$.ajax({
				url: "/ajax_login_form",
				dataType: 'html',
				success: function(response) {
					$('body.ajax .login').replaceWith(response);
				}
		    });
			$.ajax({
				url: "/ajax_big_buttons",
				dataType: 'html',
				success: function(response) {
					$('body.ajax .big_button').html(response);
				}
		    });
			$.ajax({
				url: "/ajax_slider",
				dataType: 'html',
				success: function(response) {
					$('body.ajax #slider').replaceWith(response);
					bind_sider();
				}
		    });
		    $.ajax({
				url: "/ajax_success_stories",
				dataType: 'html',
				success: function(response) {
					$('body.ajax .success_stories').replaceWith(response);
				}
		    });
			$.ajax({
				url: "/ajax_footer_navigation",
				dataType: 'html',
				success: function(response) {
					$('body.ajax .footer_nav').replaceWith(response);
				}
		    });
			$.ajax({
				url: "/ajax_stats_counter",
				dataType: 'html',
				success: function(response) {
					$('body.ajax #counter').replaceWith(response);
				}
		    });
		}
	});

	bind_sider();
	function bind_sider() {
		$("#slideout").hoverIntent(function() {
		    $(this).animate({
				left: '250px'
			}, 1000);
			$('#slideout_inner', this).animate({
				left: '0'
			}, 1000);
		}, function() {
			$(this).animate({
				left: '0px'
			}, 1000);
			$('#slideout_inner', this).animate({
				left: '-250px'
			}, 1000);
		});
	}



	$(document).ready(function() {
		$(".message-list tbody tr:not('.active')").live('click', function(e) {
			var messageRow = $(this);
			$('.message-list tr.active').removeClass('active');
			messageRow.addClass('active').removeClass('status-unread').addClass('status-read');
			messageId = messageRow.data('message-id');

			$('#message-body .message').hide();
			$('#message-body .message[data-message-id=' + messageId + ']').show();
		});
	});

	$(document).ready(function() {
		$('.filter-button').hide();
		$('.search-filters select').attr('name', 'search_filter').live('change', function() {
			$('.search-filters .filter-button').click();
		});
	});

	

	/*
	$(window).bind('load', function() {
		// after *everything* has loaded
	});
	*/

}(jQuery));


(function($){
	$.simpleWidget('uiMessage', {
		options: {
			"type": "info",
			"timestamp": new Date().getTime(),
			"duration": 10000,
			"class": ""
		},
		_create: function() {
			var data = this.element.data('message');

			// only initialize once
			if (!data) {
				this.element.hide();
				// use given message or inner html
				var messageText = this.options.message,
					messageStateClass, iconClass, msgEl, msgMarkup = [];
				if (messageText === null || messageText === "") {
					messageText = this.element.html();
					this.options.message = messageText;
				}

				// type info
				switch(this.options.type){
					case "help":
						messageStateClass = "ui-state-help";
						iconClass = "ui-icon-help";
						break;
					case "success":
						messageStateClass = "ui-state-success";
						iconClass = "ui-icon-check";
						break;
					case "error":
						messageStateClass = "ui-state-error";
						iconClass = "ui-icon-alert";
						break;
					case "info":
						messageStateClass = "ui-state-highlight";
						iconClass = "ui-icon-info";
						break;
					default:
						messageStateClass = "ui-state-highlight";
						iconClass = "ui-icon-info";
						break;
				}

				this.element.addClass('ui-message ui-widget').addClass(messageStateClass).addClass(this.options["class"]);
				// this.element.append('<div><span class="ui-icon ' + iconClass +  '" style="float:left;"></span>' + messageText + '</div>');
				this.element.append('<div>' + messageText + '</div>');
				this.element.data("message", this.options);
			}
		},
		destroy: function() {
			var data = this.element.data("message");
			this.element.removeClass('ui-message-container ui-widget');
			$(".ui-message", this.element).remove();
			this.element.html(data.message).css("display:none");
			this.element.removeData("message");
		},
		hide: function() {
			this.element.hide();
		},
		show: function(instant) {
			if (instant) {
				this.element.show();
			} else {
				this.element.fadeIn(2000).delay(this.options.duration).fadeOut(2000);
			}
		},
		showFor: function(time) {
			this.element.show();
		}

	});

	$.simpleWidget('uiMessagesList', {
		options: {
			"containerType": "div"
		},
		_create: function() {
			this.element.addClass('ui-messages-list');
		},
		destroy: function() {
			this.element.removeClass('ui-messages-list');
		},
		addMessage: function(messages) {
			var i = 0, msg = '';
			messages = ($.isArray(messages) ? messages : [ messages ]);
			for (i = 0; i < messages.length; i++) {
				msg = $('<div></div>');
				msg.appendTo(this.element);
				msg.uiMessage(messages[i]);
				msg.uiMessage('show');
			}
		},
		clear: function() {
			this.element.find('.ui-message').uiMessage("destroy");
		}
	});

})(jQuery);
