/*
	ADL ajax inline profile helper
	
	dependances:
		prototype & scriptaculous library
	
	1.0	10/Jun/08.	djmb.	Original.

*/

// Setup on window load
document.observe("dom:loaded", function () {attachProfileActions();attachFooterStatusBar(); attachWidgetActions();});

var ADL_helpers = Class.create( {
	initialize: function () {
			this.viewportPosition = null;
			this._addJavascript = [];
		},
	closeHTMLtop: function (o) {
		o.classes = ['closehandle','topright'];
		return this.closeHTML(o);
	},
	closeHTMLbottom: function (o) {
		o.classes = ['closehandle','bottomright'];
		return this.closeHTML(o);
	},
	closeHTML: function(o) {
		return '<a href="'+((o.click) ? 'javascript:'+o.click+'();' : '#')+'" class="'+((o.classes && o.classes instanceof Array) ? o.classes.join(' ') : '')+'">&nbsp;</a>';		
	},
	require: function(libraryName) {
     // for xhtml+xml served content, fall back to DOM methods
     var script = document.createElement('script');
     script.type = 'text/javascript';
     script.src = libraryName;
     document.getElementsByTagName('head')[0].appendChild(script);
  },
	getPageSize: function() {
	    var xScroll, yScroll;
	    if (window.innerHeight && window.scrollMaxY) {
	        xScroll = document.body.scrollWidth;
	        yScroll = window.innerHeight + window.scrollMaxY;
	    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	        xScroll = document.body.scrollWidth;
	        yScroll = document.body.scrollHeight;
	    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	        xScroll = document.body.offsetWidth;
	        yScroll = document.body.offsetHeight;
	    }
	    var windowWidth, windowHeight;
	    if (self.innerHeight) { // all except Explorer
	        windowWidth = self.innerWidth;
	        windowHeight = self.innerHeight;
	    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	        windowWidth = document.documentElement.clientWidth;
	        windowHeight = document.documentElement.clientHeight;
	    } else if (document.body) { // other Explorers
	        windowWidth = document.body.clientWidth;
	        windowHeight = document.body.clientHeight;
	    }
	    // for small pages with total height less then height of the viewport
	    if(yScroll < windowHeight){
	        pageHeight = windowHeight;
	    } else {
	        pageHeight = yScroll;
	    }
	    // for small pages with total width less then width of the viewport
	    if(xScroll < windowWidth){
	        pageWidth = windowWidth;
	    } else {
	        pageWidth = xScroll;
	    }
	    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	    return arrayPageSize;
	},
	adjustPageSize: function () {
		// ensure #profileBlackout fills entire page, now profileOverlay may have increased the page size
		$('profileBlackout').setStyle({height: ADL.getPageSize()[1]+'px'});
		var elm = $('profileOverlay');
		var position = elm.viewportOffset();
		var viewport = document.viewport.getDimensions();
		ADL.viewportPosition = document.viewport.getScrollOffsets(); // save in global
		if (position[1] < 0 || (position[1]+elm.getHeight()) > viewport.height) {
			new Effect.ScrollTo(elm, { duration: 0.25, offset: -40 });
		}
	},
	MCEsetup: function () {
		// setup tinyMCE editor
		tinyMCE.init({
		  mode : "exact",
		  elements: 'message',
			plugins : "emotions,safari,inlinepopups",
			theme : "advanced",
			content_css: '/style/screen.css',
			theme_advanced_buttons1 : "bold,italic,underline,fontselect,fontsizeselect,separator,forecolor,backcolor,separator,emotions,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_path : false,
			theme_advanced_resizing : true
		});			
	}
});

var ADL = new ADL_helpers();

function attachWidgetActions() {
	// attach prev/next to widgets
	$$('div.widget_one_user').each(
		function (widget) {
			var id_parts = widget.id.split('_'); // should be loguserid_{id}
			var id = id_parts[1]; // get numeric id
			$(widget).select('.previous').invoke('observe','click',previousWidgetProfile);
			$(widget).select('.next').invoke('observe','click',nextWidgetProfile);
		}
	);
}

function previousWidgetProfile(e) {
	return getRandomWidgetProfile(e);
}

function nextWidgetProfile(e) {
	return getRandomWidgetProfile(e);
}

function getRandomWidgetProfile(e) {
	var element = Event.element(e);
	var loguserid = getWidgetLoguserid(element);
	new Ajax.Request(	'/random_widget.php?ajax=1&not_loguserid='+loguserid,
					 	{ method: 'get', onComplete: displayWidgetProfile }
					);
	Event.stop(e);
}

function displayWidgetProfile(oResp, oJSON) {
	$(oJSON.replace_id).replace(oResp.responseText);
	attachWidgetActions();
	$$('div.widget_one_user').each(function (widget) { attachProfileActions(widget); } );
}

function getWidgetLoguserid(e) {
	// get loguserid from div.widget_one_user container when an child element was clicked
	var id_parts = $(e).up('div.widget_one_user').id.split('_');
	return id_parts[1];
}

function attachProfileActions(within) {
	// find all links
	var freePage = false;
	within = (within) ? within : document; // scope to search, default = docuemnt
	if (window.location.href.search(/\/free.*\.php/) != -1 || window.location.href.search(/\/index\.php/) != -1) {
		// used to selectively not attach links on free pages
		// free pages are those that match /free*.php*
		freePage = true;
	}
	if (document.getElementsByTagName) {
		var links = within.getElementsByTagName('a');
		var tinyMCEincluded = false;
		for (var i = 0; i < links.length; i++) {
			if (links[i].href.search(/\/profile\.php.*[^#]$/) != -1) {
					// its a profile link so setup on click handler
					Event.observe(links[i], "click", getProfile);
			} else if (!freePage && links[i].href.search(/\/fav.php\?action=add/) != -1) {
					// its an add favourite line so setup on click handler
					Event.observe(links[i], "click", addFavourite);
			}	else if (!freePage && links[i].href.search(/\/messages.php\?action=(reply|send_kiss)/) != -1) {
					// send a message/kiss
					Event.observe(links[i], "click", getMessageDialogue);
					if (!tinyMCEincluded) {
						ADL.require("Scripts/tiny_mce/tiny_mce.js");
						tinyMCEincluded = true;
					}
			}	else if (!freePage && links[i].href.search(/\/tellafriend.php/) != -1) {
					// tell a friend
					Event.observe(links[i], "click", getTellaFriendDialogue);
			}
		}
		// add overlay for showing profile
	  var objBody = document.getElementsByTagName("body").item(0);
		if (!$('profileOverlay')) { $(objBody).insert(new Element('div', {id: 'profileOverlay', style: 'display: none;'})); }
		if (!$('profileBlackout')) { $(objBody).insert(new Element('div', {id: 'profileBlackout', style: 'display: none;'})); }
	}
}

function attachFooterStatusBar() {
	// add footer for showing status & counts
	var objBody = document.getElementsByTagName("body").item(0);
	if (!$('footerstatusbar')) $(objBody).insert(new Element('div', {id: 'footerstatusbar'}));
	var height = $('footerstatusbar').getHeight();
	$$('body').invoke('setStyle','margin-bottom:'+(height+20)+'px;');
	new Ajax.PeriodicalUpdater('footerstatusbar', '/footerstatusbar.php', { frequency: 60, decay: 1, evalScripts: true });
}


function getProfile(e) {
	// issue ajax request for profile and setup display call back
	var element = Event.element(e);
	if (element.nodeName == 'IMG') {
		// event fired on image, so get parent link element
		element = element.up('a');
	}
	// profile link, so do the ajax thing
	showAjaxProgress(element,'fetching profile...');
	new Ajax.Request(	element.href+'&ajax=1',
					 	{ method: 'get', onComplete: displayProfile }
					);
	Event.stop(e);		
}

function getTellaFriendDialogue(e) {
	var element = Event.element(e);
	if (element.nodeName != 'A') {
		// event fired on image, so get parent link element
		element = element.up('a');
	}
	showAjaxProgress(element,'starting message editor...');
	new Ajax.Request(	element.href+'&ajax=1',
					 	{ method: 'get', onComplete: showTellaFriendDialogue }
					);
	Event.stop(e);	
}

function showTellaFriendDialogue(oResp, oJSON) {
	showProfileOverlay({HTML: oResp.responseText, click: 'hideTellaFriendDialogue'});
	attachProfileActions($('profileOverlay'));	
}

function hideTellaFriendDialogue() {
	hideProfileOverlay();
}

function getMessageDialogue(e) {
	var element = Event.element(e);
	if (element.nodeName != 'A') {
		// event fired on image, so get parent link element
		element = element.up('a');
	}
	showAjaxProgress(element,'starting message editor...');
	new Ajax.Request(	element.href+'&ajax=1',
					 	{ method: 'get', onComplete: showMsgDialogue, evalScripts: true }
					);
	Event.stop(e);
}

function showMsgDialogue(oResp, oJSON) {
	// display profile on screen in a div#profileOverlay
	showProfileOverlay({HTML: oResp.responseText, click: 'hideMsgDialogue'});
	attachProfileActions($('profileOverlay'));
}

function hideMsgDialogue() {
	hideProfileOverlay();	
}

function showProfileOverlay(options) {
	$$('select').each( function(e) {
									e.hide();
								}
						);
	$('ajax_status').hide();
	$('profileBlackout').setStyle({height: ADL.getPageSize()[1]+'px'});
	$('profileOverlay').update(ADL.closeHTMLtop(options) + options.HTML + ADL.closeHTMLbottom(options));
	$('profileBlackout').appear({to: .7, duration: 0.25});
	$('profileOverlay').appear({to: 1, duration: 0.25, afterFinish: ADL.adjustPageSize});	
}

function hideProfileOverlay() {
	if ($('profileOverlay').visible()) {
		new Effect.Fade('profileOverlay', { duration: 0.25 });
		new Effect.Fade('profileBlackout', { duration: 0.25 });
		window.scrollTo(ADL.viewportPosition.left,ADL.viewportPosition.top); // Scroll window back to original position
		// unhide selects previously hidden because of bug in IE 6
		$$('select').each( function(e) {
										e.show();
									}
							);		
	}
}

function addFavourite(e) {
	// issue ajax request for add favourite and setup display status call back
	var element = Event.element(e);
	if (element.nodeName != 'A') {
		// event fired on image, so get parent link element
		element = element.up('a');
	}
	showAjaxProgress(element,'adding favourite...');
	new Ajax.Request(	element.href+'&ajax=1',
					 	{ method: 'get', onComplete: updateAjaxStatus }
					);
	Event.stop(e);
}

function showAjaxProgress(element,msg) {
	// Display progress message at cursor
	if (!msg) msg = 'working...';
	var moveTo = Position.cumulativeOffset(element);
	if (!$('ajax_status')) {
		// create ajax_status div
		// for showing ajax results
	    var objBody = document.getElementsByTagName("body").item(0);
			$(objBody).insert(new Element('div', {id: 'ajax_status', style: 'display: none;'}));
	}
	var statusBox = $('ajax_status');
	if (statusBox) {
		//statusBox.style.left = moveTo[0]+'px';
		statusBox.style.top = moveTo[1]+'px';
		statusBox.addClassName('inprogress');
		statusBox.update('<p>'+msg+'</p>');
		new Effect.Appear(statusBox,{duration: 0.25});
	}
}

function updateAjaxStatus(oResp, oJSON) {
	// Display status message
	$('ajax_status').removeClassName('inprogress').update(((oJSON && oJSON.userClose) ? ADL.closeHTMLtop({click: 'hideAjaxStatus'}): '') + oResp.responseText);
	// function assigned to var creates enclosure, so can reference oJSON object
	if (oJSON && !oJSON.userClose) {
		hideAjaxStatus({fadeSeconds: (oJSON && oJSON.fadeSeconds) ? oJSON.fadeSeconds : 1});		
	}
}

function hideAjaxStatus(o) {
	new Effect.Fade('ajax_status',
					{ delay: ((o && o.fadeSeconds) ? o.fadeSeconds : 0), queue:'end', duration: 0.25 }
					);	// fade out status msg
}

function displayProfile(oResp, oJSON) {
	// display profile on sscreen in a div#profileOverlay
	showProfileOverlay({HTML: oResp.responseText, click:'hideProfile'});
	// enable fav links on profile overlay
	attachProfileActions($('#profileOverlay'));
	//document.observe('keydown', keyboardAction);
}

function hideProfile() {
	// hide profile overlay
	//document.stopObserving('keydown', keyboardAction); 
	hideProfileOverlay();
}

function keyboardAction(event) {
	var keycode = event.keyCode;

	var escapeKey;
	if (event.DOM_VK_ESCAPE) {  // mozilla
		escapeKey = event.DOM_VK_ESCAPE;
	} else { // ie
		escapeKey = 27;
	}

	var key = String.fromCharCode(keycode).toLowerCase();
	
	if (key.match(/x/) || (keycode == escapeKey)){ // close profile on 'x' or ESCape
		if ($('lightbox') && !$('lightbox').visible()) hideProfile();
	}
}

// rating class to handle stars
// 
var Rater = Class.create( {
	initialize: function(containerElm,optionsObj) {
		this.raterOptions = { increments: 1, maximum: 10, rating:0, onSet: null, onChange: null }; // default options
		if (optionsObj) {
			// add additional optionsn if present
			Object.extend(this.raterOptions,optionsObj);
		}
		this.raterOptions.elm = containerElm;
		var elm = $(containerElm);
		if (!elm) return false;
		if (!elm._raterSetup) {
			var ratingValue = elm.down('.ratingvalue');
			if (ratingValue) {
				this.raterOptions.rating = parseInt(ratingValue.innerHTML);
			}
			elm._raterSetup = true;
			var elmWidth = $(this.raterOptions.elm).getWidth();
			var elmWidth = (elmWidth) ? elmWidth : 300; // Hack for now
			/*
				TODO elmWidth is zero when using float over profiles, timing issue with DOM?
			*/
			this.raterOptions.rateWidth = Math.floor(elmWidth / (this.raterOptions.maximum / this.raterOptions.increments));
			Event.observe(containerElm,'click', this.setRatingListner.bind(this));
			Event.observe(containerElm,'mousemove', this.adjustVisualsListner.bind(this));
			Event.observe(containerElm,'mouseout', this.adjustVisuals.bind(this));
			this.adjustVisuals(this.raterOptions.rating);
		}
	},
	adjustVisualsListner: function(e) {
		// mousing over
		this.adjustVisuals(this.convertPositionToRating(e))
	},
	adjustVisuals: function(r) {
		if (typeof(r) != 'number') r = this.raterOptions.rating;
		$(this.raterOptions.elm).down('.ratingimg').setStyle({ backgroundPosition: '0px -'+(r*this.raterOptions.rateWidth)+'px' });
		if (this.raterOptions.onChange) this.raterOptions.onChange(r);
	},
	setRatingListner: function(e) {
		this.setRating(this.convertPositionToRating(e));
	},
	setRating: function (r,stopcallback) {
		if (this.raterOptions.onSet && !stopcallback) {
			// issue callback
			rt = this.raterOptions.onSet(r);
			if (rt) r = rt; // if return value set rating to it
		}
		this.raterOptions.rating = r;
		this.adjustVisuals(r);
	},
	getRating: function () {
		return this.raterOptions.rating;
	},
	convertPositionToRating: function(e) {
		var elm = $(this.raterOptions.elm);
		var elmX = Event.pointerX(e) - elm.cumulativeOffset()[0];
		var rating = Math.round(((elmX / this.raterOptions.rateWidth) + 0.25)*this.raterOptions.increments,0);
		return rating;
	}		
});

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function isIE() {
	return (getInternetExplorerVersion() != -1);
}

//
// Note: This file depends on the Prototype library.
//

// Automatically calls all functions in FORMALIZE.init
$(document).observe('dom:loaded', function() {
	FORMALIZE.go();
});

// Module pattern:
// http://yuiblog.com/blog/2007/06/12/module-pattern/
var FORMALIZE = (function(window, document, undefined) {
	// Private constants.
	var PLACEHOLDER_SUPPORTED = 'placeholder' in document.createElement('input');
	var AUTOFOCUS_SUPPORTED = 'autofocus' in document.createElement('input');
	var WEBKIT = 'webkitAppearance' in document.createElement('select').style;
	var IE6 = IE(6);
	var IE7 = IE(7);

	// Internet Explorer detection.
	function IE(version) {
		var b = document.createElement('b');
		b.innerHTML = '<!--[if IE ' + version + ']><br><![endif]-->';
		return !!b.getElementsByTagName('br').length;
	}

	// Expose innards of FORMALIZE.
	return {
		// FORMALIZE.go
		go: function() {
			for (var i in FORMALIZE.init) {
				FORMALIZE.init[i]();
			}
		},
		// FORMALIZE.init
		init: {
			detect_webkit: function() {
				if (!WEBKIT) {
					return;
				}

				// Tweaks for Safari + Chrome.
				$$('html')[0].addClassName('is_webkit');
			},
			// FORMALIZE.init.full_input_size
			full_input_size: function() {
				if (!IE7 || !$$('textarea, input.input_full').length) {
					return;
				}

				// This fixes width: 100% on <textarea> and class="input_full".
				// It ensures that form elements don't go wider than container.
				$$('textarea, input.input_full').each(function(el) {
					Element.wrap(el, 'span', {'class': 'input_full_wrap'});
				});
			},
			// FORMALIZE.init.ie6_skin_inputs
			ie6_skin_inputs: function() {
				// Test for Internet Explorer 6.
				if (!IE6 || !$$('input, select, textarea').length) {
					// Exit if the browser is not IE6,
					// or if no form elements exist.
					return;
				}

				// For <input type="submit" />, etc.
				var button_regex = /button|submit|reset/;

				// For <input type="text" />, etc.
				var type_regex = /date|datetime|datetime-local|email|month|number|password|range|search|tel|text|time|url|week/;

				$$('input').each(function(el) {
					// Is it a button?
					if (el.getAttribute('type').match(button_regex)) {
						el.addClassName('ie6_button');

						/* Is it disabled? */
						if (el.disabled) {
							el.addClassName('ie6_button_disabled');
						}
					}
					// Or is it a textual input?
					else if (el.getAttribute('type').match(type_regex)) {
						el.addClassName('ie6_input');

						/* Is it disabled? */
						if (el.disabled) {
							el.addClassName('ie6_input_disabled');
						}
					}
				});

				$$('textarea, select').each(function(el) {
					/* Is it disabled? */
					if (el.disabled) {
						el.addClassName('ie6_input_disabled');
					}
				});
			},
			// FORMALIZE.init.placeholder
			placeholder: function() {
				if (PLACEHOLDER_SUPPORTED || !$$('[placeholder]').length) {
					// Exit if placeholder is supported natively,
					// or if page does not have any placeholder.
					return;
				}

				$$('[placeholder]').each(function(el) {
					var text = el.getAttribute('placeholder');
					var form = el.up('form');

					function add_placeholder() {
						if (!el.value || el.value === text) {
							el.value = text;
							el.addClassName('placeholder_text');
						}
					}

					add_placeholder();

					el.observe('focus', function() {
						if (el.value === text) {
							el.value = '';
							el.removeClassName('placeholder_text');;
						}
					});

					el.observe('blur', function() {
						add_placeholder();
					});

					// Prevent <form> from accidentally
					// submitting the placeholder text.
					form.observe('submit', function() {
						if (el.value === text) {
							el.value = '';
						}
					});

					form.observe('reset', function() {
						setTimeout(add_placeholder, 50);
					});
				});
			},
			// FORMALIZE.init.autofocus
			autofocus: function() {
				if (AUTOFOCUS_SUPPORTED || !$$('[autofocus]').length) {
					return;
				}

				$$('[autofocus]')[0].select();
			}
		}
	};
// Alias window, document.
})(this, this.document);


