/*
	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>';		
	},
	addJavascript: function (jsscriptname,addOptions) {
		var options = {pos: 'body'};
		if (addOptions) {
			// add additional optionsn if present
			Object.extend(options,addOptions);
		}	
		if (this._addJavascript.indexOf(jsscriptname) == -1) {
			var th = document.getElementsByTagName(options.pos).item(0);
			var elm = new Element('script',{type: 'text/javascript', src: jsscriptname });
			$(th).insert({top: elm});
			if (options.onload) {
				$(elm).observe('load',options.onload);
				$(elm).observe('readystatechange',options.onload);
			}
			this._addJavascript.push(jsscriptname);
		} else if (options.onload) {
			// already loaded
			options.onload();
		}
	},
	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_GZ.init({
			plugins : 'emotions,safari,inlinepopups',
			themes : 'advanced',
			languages : 'en',
			disk_cache : true,
			debug : false
		});		
		tinyMCE.init({
		  mode : "textareas",
			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) {
		links = within.getElementsByTagName('a');
		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 && !isIE() && links[i].href.search(/\/messages.php\?action=(reply|send_kiss)/) != -1) {
					// send a message/kiss
					Event.observe(links[i], "click", getMessageDialogue);
			}	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');
	}
	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 }
					);
	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;
	}		
});

var LazyLoader = {}; //namespace
LazyLoader.timer = {};  // contains timers for scripts
LazyLoader.scripts = [];  // contains called script references
LazyLoader.load = function(url, callback) {
        // handle object or path
        var classname = null;
        var properties = null;
        try {
                // make sure we only load once
                if ($A(LazyLoader.scripts).indexOf(url) == -1) {
                        // note that we loaded already
                        LazyLoader.scripts.push(url);
                        var script = document.createElement("script");
                        script.src = url;
                        script.type = "text/javascript";
                        $$("head")[0].appendChild(script);  // add script tag to head element
                        
                        // was a callback requested
                        if (callback) {    
                                // test for onreadystatechange to trigger callback
                                script.onreadystatechange = function () {
                                        if (script.readyState == 'loaded' || script.readyState == 'complete') {
                                                callback();
                                        }
                                }                            
                                // test for onload to trigger callback
                                script.onload = function () {
                                        callback();
                                        return;
                                }
                                // safari doesn't support either onload or readystate, create a timer
                                // only way to do this in safari
                                if ((Prototype.Browser.WebKit && !navigator.userAgent.match(/Version\/3/)) || Prototype.Browser.Opera) { // sniff
                                        LazyLoader.timer[url] = setInterval(function() {
                                                if (/loaded|complete/.test(document.readyState)) {
                                                        clearInterval(LazyLoader.timer[url]);
                                                        callback(); // call the callback handler
                                                }
                                        }, 10);
                                }
                        }
                } else {
                        if (callback) { callback(); }
                }
        } catch (e) {
                alert(e);
        }
}

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);
}
