// -------------------------
// Global Space
// -------------------------

// Adds rounded borders in IE
/*
// Actually doesn't work fine, I figured out that using this removes 
// the margins of the main container.
Ext.onReady(function() {
  DD_roundies.addRule('#content-frame .expo ', '6px');
  DD_roundies.addRule('.pic', '6px');
  DD_roundies.addRule('#subnavigation-menu', '6px');
  DD_roundies.addRule('.current-subsection', '6px');
  DD_roundies.addRule('#content-frame .criticism', '6px');
});
*/
// -----------------
// 'Gallery' section related functions, variables and constants
// -----------------

var PAINTS_PREVIEWS_CONTAINER_ID = 'paints-preview';
var PAINTS_CONTAINER_ID = 'paints-container';

// Avoids the user to click twice on the same paint.
var lastPaintClickedId = "";

var searchQueryInURL = function() {
	if (window.location.search != "") {
		var q = window.location.search.substring(1, window.location.search.length);
		q = Ext.urlDecode(q, true);
		var imageName = q.paint + "-paint";
		var imgElem = Ext.get(imageName);
		if (imgElem) {
			imgElem.scrollHorizontalIntoView(PAINTS_CONTAINER_ID);
			lastPaintClickedId = imageName;
		}
	}
}

var onPaintPreviewClickHandler = function(linkEl, paintId, paintsContainer) {
	
	if (lastPaintClickedId != paintId) {
		Ext.get(paintId).scrollHorizontalIntoView(paintsContainer);
	}
	
	lastPaintClickedId = paintId;
	
}

var onPaintMouseOverHandler = function(event, element) {
	var imageName = getImageName(element.src);
	var descCont = Ext.get(imageName + '-desc');
	
	descCont.setStyle("display", "block");
	descCont.setStyle("opacity", .7);
	var xy = event.getXY();
	
	descCont.setXY([xy[0] + 15, xy[1] + 15]);

}

var onPaintMouseOutHandler = function(event, element) {
	var imageName = getImageName(element.src);
	var descCont = Ext.get(imageName + '-desc');
	
	descCont.setStyle("display", "none");
}

function registerPaintPreviews(containerId) {

	var container = Ext.get(containerId);
	
	// Get links to previews
	var previewsLinks = container.query('a');
	
	for (var i = 0, len = previewsLinks.length; i < len; i++) {
		
		var link = previewsLinks[i];
		
		var paintName = getImageName(link.href);
		
		var paintId = paintName + '-paint';
		var paintsCont = PAINTS_CONTAINER_ID;
		var paintDescId = paintName + '-desc';
		
		var paint = Ext.get(paintId).first('img');
		
		Ext.get(link).on('click', onPaintPreviewClickHandler.createCallback(Ext.get(link), paintId, paintsCont), null, { stopEvent : true });
		paint.on('mousemove', onPaintMouseOverHandler);
		paint.on('mouseout', onPaintMouseOutHandler);
	}
	
}

// HashMap containing descriptions for the images
// Descriptions are loaded and stored at onDomReady.
var _paintDescriptions = {};

function _onPicMouseOver(extEvent, elem) {
	var descEl = Ext.get('pic-desc');
	var xy = extEvent.getXY();
	
	if (_paintDescriptions[elem.src]) {
		descEl.dom.innerHTML = _paintDescriptions[elem.src];
		descEl.setXY([xy[0] + 15, xy[1] + 15]);
		descEl.setStyle('display', 'block');
	}	
}

function _onPicMouseOut(extEvent, elem) {
	Ext.get('pic-desc').setStyle('display', 'none');
	Ext.get('pic-desc').setXY([0,0]);
}

/*
  Registers onMouseMove and onMouseOut events to pictures in the page.
  The function will use the text in the 'alt' attribute to generate
  a div which will show information about the picture.
  Not all the images will be used to generate this 'information div', but
  the ones that match with a specific CSS selector.
  
  Actual selector: #content-frame .expo-pictures img
 */
function registerPaintDescriptionsRollovers() {
	
	var imagesEls = Ext.query("#content-frame .expo-pictures img");
	
	for (var i = 0, len = imagesEls.length; i < len; i = i + 1) {
		var el = imagesEls[i];
		if (el.alt) {
			_paintDescriptions[el.src] = el.alt;
			el.alt = "";
			
			el = Ext.get(el);
			el.on('mousemove', _onPicMouseOver);
			el.on('mouseout',_onPicMouseOut);
		}
	}
	
	Ext.get('pic-desc').setStyle('opacity', .7);
}


// ------------------------
// Utilities
// ------------------------
function d () {
		if (!Ext.isIE)
			console.log(arguments);
}

function getImageName(pathToImage) {

	// "www.domain.com/dir/to/image.jpg" -> ["www.domain.com", "dir", "to", "image.jpg"]
	var unfilteredPaintName = pathToImage.split(/\//);
	
	// ["www.domain.com", "dir", "to", "image.jpg"] -> "image.jpg"
	unfilteredPaintName = unfilteredPaintName[unfilteredPaintName.length - 1];
	
	// "image.jpg" -> "image"
	var  paintName = unfilteredPaintName.slice(0, unfilteredPaintName.length - 4);
	
	return paintName;
	
}


// Customized scrollIntoView function. Supports horizontal scroll animation.
// Arguments:
// @container: the container to be scrolled.
// @callback: a function that will be called after the scrolling.
Ext.apply(Ext.Element.prototype, {

    scrollHorizontalIntoView : function(container, callback){
        var c = Ext.getDom(container) || Ext.getBody().dom;
		var callback = callback || function() {};
        var el = this.dom;

        var o = this.getOffsetsTo(c),
            l = o[0] + c.scrollLeft,
            t = o[1] + c.scrollTop,
            b = t+el.offsetHeight,
            r = l+el.offsetWidth;

        var ch = c.clientHeight;
        var ct = parseInt(c.scrollTop, 10);
        var cl = parseInt(c.scrollLeft, 10);
        var cb = ct + ch;
        var cr = cl + c.clientWidth;

        if(el.offsetHeight > ch || t < ct){
        	c.scrollTop = t;
        }else if(b > cb){
            c.scrollTop = b-ch;
        }
		
        c.scrollTop = c.scrollTop; // corrects IE, other browsers will ignore
		
		var margin = Math.floor((Ext.get(c).getWidth() - this.getWidth()) / 2);
		var scrollXPosition;

		if(el.offsetWidth > c.clientWidth || l < cl){
			scrollXPosition = l - margin;
			//c.scrollLeft = l - margin;
		}else if(r > cr){
			scrollXPosition = r - c.clientWidth + margin;				
			//c.scrollLeft = r-c.clientWidth + margin;
		}
		//c.scrollLeft = c.scrollLeft;
		
		Ext.get(container).animate(
			{ scroll : { "to" : [scrollXPosition, 0] }	},
			1,
			function() { 
				c.scrollLeft = c.scrollLeft; // IE 6 fix
				callback();
			},
			"easeBoth",
			"scroll"
		);
		
        return this;
    }
});
