var RS = RS || {};

$(function() { // Init
	RS.search_field = $('#search input[@name=q]');
	
	RS.cookie = {};
	$(document.cookie.split('; ')).each(function() {
		var t = this.split('=');
		RS.cookie[t[0]] = t[1];
		if (t[0].substr(0, 4) == 'SESS') RS.has_cookie = 1;
	});
	
	var matches = /pro_hdr=(\d+)/.exec(window.location.hash);
  if (matches) {
    RS.set_cookie('pro_hdr', matches[1]);
    var matches = /(.*)#(.*)$/.exec(window.location.href);
    var rem = matches[2].replace(/pro_hdr=(\d+)/, '');
    if (rem.length) location.replace(matches[1] + '#' + rem);
  }
  
  if (RS.cookie.pro_hdr) {
		$('<div class="pro_hdr"></div>').prependTo('#container').load('/pro_hdr/' + RS.cookie.pro_hdr, RS.attachBehaviors);
  }
  
	RS.set_search_field();
  
  if (RS.mrp) {
  	$.get('/js/geolocate/' + RS.mrp + (RS.ex_search ? '/' + encodeURIComponent(RS.ex_search) : ''));
  }
  
	RS.Search(RS.search_field, 'search/autocomplete', function(e, key_event, anchor) {
		window.location.assign(anchor.attr('href'));
		return false;
	}, function(result) {
		return '<a href="/' + result.path + '"><span> ' + result.title + '</span></a>';
	}, function(pos, input, container) {
		container.css({
			right: $('#container').width() - pos.x - input.width() - 7 + 'px',
			top: pos.y + input.height() + 5 + 'px'
		});
	});
	
	RS.fad();
	RS.nav_init_ie6();
	RS.attachBehaviors();
});

RS.get_search_phrase = function() {
	var matches, pattern
		loc = window.location.toString(),
		ref = document.referrer.toString();
	
	if (loc.indexOf('.realself.com/search') != -1) {
		matches = /q=([^&#]+)/.exec(loc);
	}
	else {
		if (ref.indexOf('.realself.com/') != -1) {
			return -1;
		}
		
		$(['q','query','p']).each(function() {
			if ((matches = new RegExp("[&\/]" + this + "=([^&?]+)").exec(ref)) != null) {
				RS.ex_search = matches[1];
				return false;
			}
		});
	}
	
	if (matches != null) {
		return unescape(matches[1].replace(/\+/g, ' ')).replace(/^(?:www|test).realself.com/, '').replace(/^site:[^\s]+\s+/, '');
	}
	return -1;
}

RS.set_search_field = function() {
	var ph = RS.get_search_phrase();
	if (ph != -1) RS.set_cookie('rs_search_phrase', ph, 1);
	
	if (document.location.href.indexOf('search.html') != -1) {
		if (RS.cookie.rs_search_phrase) {
			RS.search_field.val(unescape(RS.cookie.rs_search_phrase.replace(/\+/g, ' ')));
		}
	}
}

RS.set_cookie = function(c_name, value, expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) +'; path=/';
	RS.cookie[c_name] = value;
}

/**
 * Search autocomplete
 */
RS.Search = function(input_selector, search_handler, enter_handler, hook_link, hook_position, url_extension, append_to) {
	var timeout, container, input = $(input_selector), sliding = false;
	if (!url_extension) url_extension = '';
	
	if (input.size() == 0) return;
	
  if (!append_to) append_to = '#container';
  
  container = $('<div class="autocomplete_search"></div>').hide().appendTo(append_to).mousedown(function(e) {
		e.stopPropagation();
	});
	
	var pos = RS.absolutePosition(input.get(0), append_to);
	if (hook_position) {
		hook_position(pos, input, container);
	}
	else {
		container.css({
			left: pos.x + 'px',
			top: pos.y + input.height() + 6 + 'px'
		});
	}
  
  input.bind('option-select', enter_handler).bind('option-select', function() {
  	hide_search();
  }).focus(function() {
		$(document.body).mousedown(hide_search);
	}).blur(function() {
		$(document.body).unbind('mousedown', hide_search);
	});
	
	RS.poll_input(input, suggest).arrow_menu(input, container);
	
	function suggest(e, val) {
		if (val.length <= 1 || val.length >= 30) {
			hide_search();
			return;
		}
		
		if (typeof search_handler == 'string') {
			$.getJSON('/' + search_handler + '/' + val + url_extension, parse_results);
		}
		else {
			search_handler(val, parse_results);
		}
	}

	function parse_results(results) {
		if (!results || !results.length) {
			hide_search();
			return;
		}
		
		container.empty();

		$(results).each(function() {
			var a = $(hook_link(this, input)).click(hide_search);
			$('<div></div>').append(a).appendTo(container);
		});

		if (container.is(':hidden')) {
			container.show();
		}
	}
	
	function hide_search() {
		if (container.is(':visible') && !sliding) {
			sliding = true;
			container.slideUp('fast', function() {
				sliding = false;	
			});
		}
	}
};

RS.nav_init_ie6 = function() {
	if (navigator.userAgent.indexOf('MSIE 6') != -1) {
		var
			h = function() { $(this).addClass('hover'); },
			uh = function() { $(this).removeClass('hover'); };
		$('#nav > li, .pro_flag, .hoverable').hover(h, uh);
	}
}

RS.pro_flags = function() {
	var flag_html = {
		isc: {
			img: 'injectable-safety.gif',
			body: 'This doctor is active in the Physicians Coalition for Injectable Safety, an alliance of specialty physician organizations dedicated to cosmetic injectable safety.<br><a href="http://www.injectablesafety.org" target="_blank" rel="nofollow">Learn more</a>'
		},
		asaps: {
			img: 'asaps-member.gif',
			body: 'This doctor is a board certified surgeon who is an active member of the American Society for Aesthetic Plastic Surgery (ASAPS).<br /> ASAPS is a leading association for aesthetic plastic surgeons. <a href="http://www.surgery.org" target="_blank" rel="nofollow">Learn more</a>'
		},
		top: {
			img: 'top-participant.gif',
			body: 'Top participants earn this badge by routinely posting and linking to RealSelf.com from their website.'
		},
		fps: {
			img: 'fps-member.png',
			body: 'This facial plastic surgeon is a member of the American Academy of Facial Plastic and Reconstructive Surgery (AAFPRS), the world\'s largest association of facial plastic and reconstructive surgeons. <a href="http://www.aafprs.org" target="_blank" rel="nofollow">Learn more</a>'
		},
		asds: {
			img: 'asds-member.gif',
			body: 'This board-certified dermatologist is an active member of the American Society for Dermatologic Surgery (ASDS). The ASDS and its more than 5,000 members are at the forefront of the development of safe, in-office procedures to help maintain the health and beauty of the skin. <a href="http://www.asds.net" target="_blank" rel="nofollow">Learn more</a>'
		}
	}
	
	for(type in flag_html) {
		$('.pro_flag.' + type).each(function() {
			if (!$('.' + type, this).size()) {
				var html = '<div class="' + type + ' pro-flag-flag"><img src="/themes/renewal/img/' + flag_html[type].img + '">';
				if (!RS.flags_hide_hover) {
					html += '<div>' + flag_html[type].body + '</div>';
				}
				html += '</div>';
				$('a', $(this).append(html)).click(RS.flag_click);
			}
		});
	}
	
	var pf = $('.pro_flag_container');
	if (pf.size() && typeof is_pro_page == 'undefined') {
		pf.css({ height: $('> > div', pf).length * 29 + 'px' });
	}
	$('.pro-flag-flag:last-child div', pf).css({ left: 'auto', right: '0px' });
	
	$('.pro_flag > div, .pro_cert .hover_mark', this).hover(
		function() {
			$(this).addClass('hover').css({ zIndex: 4 });
		},
		function() {
			$(this).removeClass('hover').css({ zIndex: '' });
		}
	);
}

RS.flag_click = function() {
	pageTracker._trackPageview("/asaps_click/");
}

RS.fad = function() {
	var fad = $('#left_nav .find-a-doctor-link');
	if (fad.size()) {
		function click_body() {
			$('.find-a-doctor, #shadowbox').remove();
			$(this).unbind('mousedown', click_body);
		}
		
		var treatment = $('input[@name=treatment-name]').val();
		var treatment_nid = $('input[@name=treatment-nid]').val();
		var a = $('<a href="#find-a-doctor">Find a doctor</a>').click(function() {
			$(this).css({ outline: 'none' });
			var pos = RS.absolutePosition(this);
			var an = RS.indexOf(['a','e','i','o','u'], treatment.substr(0,1).toLowerCase()) > -1 ? 'n' : '';
			var d = $(
				'<div class="find-a-doctor"><div class="close_button">X</div>' +
					'<h1 style="margin: 0 20px 7px 0;">Find a' + an + ' ' + treatment + ' doctor</h1>' +
					'<form class="find-form oh"><label style="line-height: 22px; margin: 0 5px 0 0" class="fl"><b style="margin-right: 23px">Enter your location:</b> <input type="text"/></label> <input type="submit" value="Find a doctor" class="fl" /><img src="/themes/renewal/img/ajax-loader-inline.gif" class="pr" style="left: 7px; top: 3px; display: none" /></form>' +
				'</div>'
			).css({ left: pos.x + 'px', top: pos.y + 18 + 'px' }).appendTo(document.body).mousedown(function(e) { e.stopPropagation() });
			
			RS.shadowbox();
			$('.close_button', d).mousedown(function() { $(document.body).trigger('mousedown'); });
			
			var input = $('input[@type=text]', d).focus(RS.gmaps.init);
			$('form', d).submit(function() {
				var val = input.val();
				if (val.length) { 
					$('img', d).show();
					RS.gmaps.geocode(val, function(point) {
						if (point) {
							$.getJSON('/js/find-a-doctor/' + point.y + '/' + point.x + '?t-nid=' + treatment_nid, parse_results);
						}
						else {
							$('img', d).hide();
							alert("No matches were found. Try searching again.");
						}
					});
				}
				return false;
			});
			
			function parse_results(data) {
				if (data.length) {
					window.location = '/' + data[0].path + '/' + treatment.replace(/\s+/, '-');
				}
				else {
					$('img', d).hide();
					alert('No matches were found. Try searching again.');
				}
			}
			
			input.get(0).focus();
			return false;
		});
		fad.empty().append(a);
	}	
}

RS.attachBehaviors = function() {
	RS.pro_flags();
	
	$('.pro-more-info').click(function() {
	  RS.hide_popups();
	  var matches = /(\d+)/.exec(this.href);
	  var popup = RS.create_popup('pro-more-info-popup', 1).attr('src', '/form/pro-more-info/' + matches[1] + ($(this).is('.skip-filter') ? '&consultation=yes' : '')).css({
      left: Math.floor(($(document.body).width() - 640) / 2) + 'px',
      top: 100 + (document.documentElement.scrollTop || document.body.scrollTop) + 'px'
    });
	  return false;
	});
	
	$('.action.ask').click(function() {
	  RS.hide_popups();
	  var popup = RS.create_popup('question-form-popup', 1).attr('src', '/form/ask').css({
      left: Math.floor(($(document.body).width() - 640) / 2) + 'px',
      top: 40 + (document.documentElement.scrollTop || document.body.scrollTop) + 'px',
      width: '640px'
    })
	  return false;
	});
	
	$('.fwdlink').click(function() {
		if ($('#fwdform:visible').size()) {
			RS.hide_popups();
			return false;
		}
		
		RS.hide_popups();
		var l = this;
		var popup = RS.create_popup('fwdform', 0, 1).css('width', '320px').attr('src', '/form/forward/' + $(this).find('input').val()).bind('popup_loaded', function() {
			var pos = Drupal.absolutePosition(l), pad = 10, de = document.documentElement;
			pos.x -= Math.floor(popup.width() / 2 - l.offsetWidth / 2);
			var w = popup.width() + pad, h = popup.height() + pad;
			if (pos.x + w > document.body.offsetWidth) {
				pos.x = document.body.offsetWidth - w;
			}
			else if (pos.x < 0 + pad) {
				pos.x = 0 + pad;
			}
			
			pos.y += 20;
			var max_h = (de.scrollTop || document.body.scrollTop) + de.clientHeight - h - pad;
			if (pos.y > max_h) pos.y = max_h;
		
			popup.css({ left: pos.x + 'px', top: pos.y + 'px' });
		});
		
		return false;
	});
}

RS.indexOf = function(arr, obj) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == obj) {
			return i;
		}
	}
	return -1;
}

RS.absolutePosition = function (el, inside) {
	var obj = el, pos = { x: 0, y: 0 };
	
	do {
		pos.x += obj.offsetLeft;
		pos.y += obj.offsetTop;
	}
	while((obj = obj.offsetParent) && (!inside || !$(obj).is(inside)));
	
  return pos;
};

RS.create_popup = function(id, shadowbox, no_loader) {
	var popup = $('#' + id);
	
	var t = Math.floor((document.documentElement.scrollTop || document.body.scrollTop) + 150);
  if (t < 0) t = 0;
	
	if (!popup.size()) {
		popup = $('<iframe id="' + id + '" class="global_popup" frameborder="0" border="0"></iframe>').appendTo(document.body);
	}
	
	if (!no_loader) {
		if (!RS.throbber || !RS.throbber.size()) {
	  	RS.throbber = $('<div class="throbber"><img src="/themes/renewal/img/ajax-loader.gif" /></div>').appendTo(document.body);
		}
		RS.throbber.css('top', t + 'px').show();
	}
	
	function pl() {
    popup.show();
    setTimeout(function() {
    	popup.trigger('popup_loaded');
    }, 10);
    $(document).unbind('popup_loaded', pl);
  }
	$(document).bind('popup_loaded', pl);
  
  if (shadowbox) RS.shadowbox();
	
	return popup;
}

RS.shadowbox = function() {
	var sb = $('#shadowbox');
	if (sb.size()) {
	  sb.css('opacity', 0).show();
	}
	else {
		sb = $('<div id="shadowbox"></div>').css({ opacity: 0, height: document.documentElement.scrollHeight + 'px' }).appendTo(document.body);
	}
	sb.fadeTo('fast', 0.3);
}

RS.hide_popups = function() {
	$('.global_popup, #shadowbox').hide();
	return false;
}

// Input polling
RS.poll_input = function(input, callback, delay) {
	var input = $(input), lookup_val = '', interval, timeout;
	
	if (!delay) delay = 400;
	if (callback) input.bind('poll-fire', callback);
	
	function start_polling() {
		lookup_val = '';
		stop_polling();
		interval = setInterval(fire_poll, 200);
		fire_poll();
	}
	
	function fire_poll() {
		var val = encodeURIComponent($.trim(input.val().replace(/\//g, '').replace(/\s+/g, ' ')));
		if (val != lookup_val) {
			lookup_val = val;
			
			clearTimeout(timeout);
			timeout = setTimeout(
				function() { $(input).trigger('poll-fire', [val]); },
				delay
			);
		}
	}
	
	stop_polling = function() {
		clearInterval(interval);
	}
	
	input.focus(start_polling).blur(stop_polling).attr('autocomplete', 'off');
	return RS;
}

// Arrowkey-enabled menus
RS.arrow_menu = function(input, container) {
	var selected, handled = false, form = input.get(0).form ? input.get(0).form : null;
	
	input.focus(function() {
		$(document).keydown(_key);
		if (form) $(form).submit(form_submit);
	}).blur(function() {
		$(document).unbind('keydown', _key);
		if (form) $(form).unbind('submit', form_submit);
	});
	
	function form_submit(e) {
		if (handled) {
			return false;
		}
	}
	
	function _key(e) {
		if (selected && !selected.get(0).parentNode.parentNode) selected = null; // Detect item removal
		if (selected) selected.removeClass('selected');
		
		var code = e.keyCode || e.which;
		switch(code) {
			case 38:
			case 40:
				var n = selected ? selected.parent()[code == 40 ? 'next' : 'prev']('div') : $('div:' + (code == 40 ? 'first' : 'last') + '-child', container);
				selected = n.size() ? n.children('a') : null;
				e.preventDefault();
			break;
			
			case 13: // Enter
				handled = false;
				if (selected) {
					input.trigger('option-select', [e, selected, input]);
					e.preventDefault();
					handled = true;
				}
			break;
		}
		
		if (selected) {
			selected.addClass('selected');
		}
	}
	return RS;
}

RS.dropdown = function(options, init_val) {
	var output = '';
	for (var val in options) {
		output += '<a href="#' + options[val] + '" class="option val-' + val + '">' + options[val] + '</a>';
	};
	var el = $('<div class="drop-down"><div class="inner">' + output + '</div></div>')
	var options_el = $('.inner', el).hide();
	
	if (!init_val) {
		for (var i in options) {
			init_val = i;
			break;
		}
	}
	
	$('<a href="#' + options[init_val] + '"class="selected option">' + options[init_val] + '</a>').appendTo(el).mousedown(function() {
		if (options_el.is(':visible')) {
			options_el.hide();
			$(document.body).unbind('mousedown', cancel);
		}
		else {
			options_el.show();
			$(document.body).mousedown(cancel);
		}
	});
	
	$('.option', options_el).mousedown(function() {
		if (options_el.is(':visible')) {
			options_el.hide();
			el.trigger('change', [/val-([^\s]+)/.exec(this.className)[1]]);
		}
	});
	
	$('.option', el).click(function() { return false; });
	
	function cancel(e) {
		if ($(e.target).parents('.drop-down').size() == 0) {
			$(this).unbind('mousedown', cancel);
			options_el.hide();
		}
	}
	
	return el;
}

RS.load_script = function(src) {
	var s = document.createElement("script");
	s.src = src;
	s.type = 'text/javascript';
	document.getElementsByTagName('head')[0].appendChild(s);
}

RS.gmaps = (function(init_callback) {
	var geocoder, init_callback = null;
	
	var me = {
		loaded: false,
		
		init: function(callback) {
			if (RS.google_key && !me.loaded) {
				if (callback) init_callback = callback;
				RS.load_script('http://maps.google.com/jsapi?callback=RS.gmaps.onload&key=' + RS.google_key);
				me.loaded = true;
			}
			else {
				callback();
			}
		},
		
		onload: function() {
			google.load("maps", "2", { callback: init_callback || function(){} });
		},
		
		geocode: function(string, callback) {
			if (!geocoder) geocoder = new GClientGeocoder();
			geocoder.getLatLng(string, callback);
		}
	}
	return me;
})();