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

*/

// Setup on window load
Event.observe(window, 'load', function (e) {attachProfileActions();attachFooterStatusBar();});

var viewportPosition = null;

function attachProfileActions() {
	// find all links
	var freePage = false;
	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 = document.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;');
	//console.log("height: "+height);
	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');
	}
	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();
								}
						);
	$('profileBlackout').setStyle({height: getPageSize()[1]+'px'});
	var closeHTML = '<p align="right"><a href="javascript:hideProfile();"><img src="images/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.7});
	$('profileOverlay').appear({to: 1, afterFinish: adjustPageSize});
	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();
	}
}
