/*
	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 viewportPosition = null;

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

			}
		}
	
		// add overlay for showing profile
	    var objBody = document.getElementsByTagName("body").item(0);
        var profileOverlay = document.createElement("div");
        profileOverlay.setAttribute('id','profileOverlay');
        profileOverlay.style.display = 'none';
        objBody.appendChild(profileOverlay);
        var profileBlackout = document.createElement("div");
        profileBlackout.setAttribute('id','profileBlackout');
        profileBlackout.style.display = 'none';
		//profileBlackout.appendChild(profileOverlay);
        objBody.appendChild(profileBlackout);
	}
}

function attachFooterStatusBar() {
	// add footer for showing status & counts
	var objBody = document.getElementsByTagName("body").item(0);
	var footerStatusBar = document.createElement("div");
	footerStatusBar.setAttribute('id','footerstatusbar');
	objBody.appendChild(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 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);
        var ajax_status = document.createElement("div");
        ajax_status.setAttribute('id','ajax_status');
        ajax_status.style.display = 'none';
        objBody.appendChild(ajax_status);
	}
	var statusBox = $('ajax_status');
	if (statusBox) {
		//statusBox.style.left = moveTo[0]+'px';
		statusBox.style.top = moveTo[1]+'px';
		statusBox.update('<p class"inprogress">'+msg+'</p>');
		new Effect.Appear(statusBox);
	}
}

function updateAjaxStatus(oResp, oJSON) {
	// Display status message
	$('ajax_status').update(oResp.responseText);
	// function assigned to var creates enclosure, so can reference oJSON object
	var delaySeconds = 1; // delay before fade
	if (oJSON && oJSON.fadeSeconds) {
		delaySeconds = oJSON.fadeSeconds; // if passed in ajax header modify delay seconds
	}
	new Effect.Fade('ajax_status',
					{ delay: delaySeconds, queue:'end' }
					);	// fade out status msg
}

function displayProfile(oResp, oJSON) {
	// display profile on sscreen in a div#profileOverlay
	var objBody = document.getElementsByTagName("body").item(0);
	// hide selects because of bug in IE 6
	$$('select').each( function(e) {
									e.hide();
								}
						);
	$('ajax_status').hide();
	$('profileBlackout').setStyle({height: getPageSize()[1]+'px'});
	var closeHTML = '<p class="txtright"><a href="javascript:hideProfile();"><img src="sysimages/lightbox/closelabel.gif"></a></p>';
	$('profileOverlay').update(closeHTML + oResp.responseText + closeHTML);
	// enable fav links on profile overlay
	$$('#profileOverlay a').each( function (link) {
										if (link.href.search(/\/fav.php\?action=add/) != -1) {
											// its an add favourite line so setup on click handler
											Event.observe(link, "click", addFavourite);
										}
								   }
								);
	$('profileBlackout').appear({to: .7, duration: 0.5});
	$('profileOverlay').appear({to: 1, duration: 0.25, afterFinish: adjustPageSize});
	//new Rater('rating'); // add rating code hook
	document.observe('keydown', keyboardAction);
}

function adjustPageSize() {
	// ensure #profileBlackout fills entire page, now profileOverlay may have increased the page size
	$('profileBlackout').setStyle({height: getPageSize()[1]+'px'});
	var elm = $('profileOverlay');
	var position = elm.viewportOffset();
	var viewport = document.viewport.getDimensions();
	viewportPosition = document.viewport.getScrollOffsets(); // save in global
	if (position[1] < 0 || (position[1]+elm.getHeight()) > viewport.height) {
		new Effect.ScrollTo(elm, { duration: 0.5 });
	}
	/* old scroll method
	if ($('profileOverlay').scrollIntoView) {
		// If browser supports scroll into view
		$('profileOverlay').scrollIntoView();
	}
	*/
}

function hideProfile() {
	// hide profile overlay
	document.stopObserving('keydown', keyboardAction); 
	new Effect.Fade('profileOverlay');
	new Effect.Fade('profileBlackout');
	window.scrollTo(viewportPosition.left,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 getPageSize(){

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

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) {
		if (this.raterOptions.onSet) {
			// 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;
	}		
});
