﻿/*
general.js for www.ayanambu.com - ajaxed website site
Based on Prototype 1.6.0 and script.aculo.us 1.8.0
Built on MODx 0.9.6.1 - the best PHP CMF
Date: October 2007 - January 2008
Version: 2.1
Developer: S. Cmakal
*/
var config = { 	site_domain: 'ayanambu.com', 
				email: 'info', 
				browserIE: false, 
				effect_duration: 0.75, 
				default_title: 'Aya Nambu', 
				portfolio_descHTML: '<h2 id="portfolio_desc">Select your section...</h2>', 
				main_imageHTML: '<img id="main_image_img" src="/" alt="" width="530" height="380" title="" />',
				image_base: 'assets/', 
				ofs_width: 10,
				update_params: '&template=portfolio_page_ajax',
				request_embed_params: '&template=portfolio_page_embed_ajax',
				message_pre: '&laquo;&nbsp;',
				message_image: 'Mouse over the image to see the details',
				message_video: 'Click the play button to watch the video',
				min_thumbs_slider: 9,
				highlight_width: 82,
				loadImage: false,
				highlight_height: 95 };

// Prototype.Browser.IE == true

/* Slider variables */
var currentSliderPosition = 0;
var gallery_pane_width = 0;
/* END: slider variables */
var sliderThumb;
var mainImageDims = Array();
var mainImagePos = [55, 85]; //too bad, too bad...
var draggableHighlight = ''; //store the draggable action in a variable
var enlarge_index = 4; //how many times is the enlargement bigger than main_image
var timer = '';
var show_enlarged_image = true;
var pageTracker;

Event.observe(window, 'load', init, false);
  
function init(e){
	browserDetect();
	$('temp').hide();
	
	/* Attach menu events */
	/*if ($('top_menu')) { 
		$A($('top_menu').down().getElementsByTagName('a')).each(function(i){
			//if (!i.href.startsWith('http://')) { Event.observe(i, 'click', getGenericContent, false); } 
			Event.observe(i, 'click', getGenericContent, false);
		});
	}*/
	/* end: Attach menu events */

	$$('#thumbnail_list li a').each(function(el, cnt){
		if ($('main_image_img') && $('main_image_img').src.indexOf(gup('main_image', el.href)) !== -1) {
			var con = '&';
			if (window.location.href.indexOf('?') == -1) { con = '?'; }
			var append = '';
			if (gup('enlarged_image', el.href) !== false) { 
				append = '&enlarged_image=' + gup('enlarged_image', el.href); 
			}
			
			config.loadImage = window.location.href + con + 'main_image=' + gup('main_image', el.href) + append;
		}
	});

	//main_image
	if (typeof _gat !== 'undefined') {
		pageTracker = _gat._getTracker("UA-4395041-2");
		pageTracker._initData();
		//pageTracker._setVar('my_home');
	}
	doStuff();  //attach events, links blurring, build conntrol elements and more
	
	$$('.gallery').each(function(el){
		el.current = 0;
		el.select('.body li.renderHidden').each(function(elem){
			elem.hide();
		});
		el.select('.controls li').each(function(elem, cnt){
			elem.item = cnt;
			Event.observe(elem.down(), 'click', function(e){
				var elem = Event.findElement(e, 'li');
				var all_elem = elem.up(1).select('.body li');
				all_elem.each(function(elem){
					elem.hide();
				});
				all_elem[elem.item].show();
				e.stop();
			}, false);
		});
	});
	
	$$('.renderHidden, .showJsOnly').each(function(i){
        i.removeClassName('renderHidden');
        i.removeClassName('showJsOnly');
    });
}
/* attach events, links blurring, build conntrol elements and wharever is needed for new ajaxed elemetns */
function doStuff(elem, url){
	url = url || window.location.href;
	if (typeof pageTracker !== 'undefined') pageTracker._trackPageview(url);
	/* */
	$$('.carousel').each(function(el){
		all_li = el.select('li');
		el.count = all_li.length - 1;
		all_li.each(function(elem, cnt){
			if (cnt !== el.count) {
				new Effect.Opacity(elem, {duration: 0, to: 0});
				elem.hide();
			}
		});
		el.current = el.count;
		new PeriodicalExecuter(function(e){
			if (el.count == el.current) {
				next = 0
			} else {
				next = el.current + 1;
			}
			new Effect.Opacity(all_li[el.current], {duration: 1, from: 1, to: 0, afterFinish: function() {
				all_li[el.current].hide();
				new Effect.Opacity(all_li[next], {duration: 0.5, from: 0, to: 1, beforeStart: function(){
					all_li[next].show();
				},
				afterFinish: function() {
					el.current = next;
				}});
			}});
		}, 5)
	});
	/* */
	/* generic stuff - remove anchor link blurring - global or element only */
	if (elem) {
		$A($(elem).getElementsByTagName('a')).each(function(i){
			Event.observe(i, 'focus', linkBlurring, false);
		});
	} else {
		$A(document.getElementsByTagName('a')).each(function(i){
			Event.observe(i, 'focus', linkBlurring, false);
		});
	}
	/* portfolio index */
	if ($('image_list')) {
		$A($('image_list').getElementsByTagName('a')).each(function(i, cnt) {
			Event.observe(i.down(), 'mouseover', showTitle, false);
			i.down().next('div').hide();
			Event.observe(i, 'click', getGenericContent, false);
		});
	}
	/* contact us page */
	if ($('aya_email')){
		$('aya_email').replace('<a href="mailto:' + config.email + '@' + config.site_domain + '">' + config.email + '@' + config.site_domain + '</a>');
	}
	/* portfolio details */
	if ($('highlight_box')) { $('highlight_box').remove(); }

	if ($('thumbnailer')) { createThumbsControl(); }  //if the thumbnailer is present create the controls
	var tmp = $('content_wrapper').getElementsByTagName('h1');
	//assume that the first H1 is the page header
	if (tmp.length > 0){
		document.title = tmp[0].innerHTML;
	} else {
		document.title = config.default_title;
	}
	if ($('image_list')) {  //we are on portfolio page
		tmp = $('content_wrapper').down();
		$('content_wrapper').down().remove();
		insert_el = config.portfolio_descHTML;
		Element.insert($('content_wrapper'), { 'top': insert_el});
		Element.insert($('content_wrapper'), { 'top': tmp});
	}
	
}

function getGenericContent(e){
	var link = Event.findElement(e, 'a');
	requestContent(link.href, 'content_wrapper', true);
	e.stop();
	return false;
}

/* Creates thumbnail controller, adds events*/
function createThumbsControl() {
			var insert_el = Builder.node('div', {id: 'enlarged_image', style: 'display: none;'},[
							Builder.node('div', {id: 'enlarged_image_inner'}, [
								Builder.node('div', {id: 'enlarged_image_inner_w'}, [
									Builder.node('img', {id: 'enlarged_image_img', src: config.image_base + 'images/elements/blank.gif', alt:'', width: '2120', height: '1520', title: 'Enlarged image'})
								])
							])
						]);

			Element.insert('main_window', insert_el);

			// insert_el = Builder.node('div', {id: 'highlight_box', style: 'display: none; width: ' + highlightWidth + 'px; height: ' + highlightHeight + 'px; '});
			// Element.insert('content', insert_el);
			createHighlightBox();
			
			var thumbs = $A($('thumbnail_list_wrapper').getElementsByTagName('a'));
			if (thumbs.length >= config.min_thumbs_slider) {
				buildSlider();
			}

			gallery_pane_width = $A($('thumbnail_list_wrapper').getElementsByTagName('a')).length * 109;
			gallery_pane_width += config.ofs_width;
			$('thumbnail_list_wrapper').setStyle({
			    width: gallery_pane_width + 'px'
			});
			thumbs.each(function(i){
				if (gup('embed', i.href) == 'true') {
					Event.observe(i, 'click', mainObjectUpdate, false);  //handle video
				} else {
					Event.observe(i, 'click', mainImageUpdate, false);
				}
			});

			/* Change styling for ajaxed version */
			$('thumbnail_list_wrapper').down().toggleClassName('first_ajax');
			$('thumbnail_list').setStyle({
				'overflow': 'hidden',
				height: '76px',
				clip: 'rect(0 905px 76px 0)'
			});

			/*draggableHighlight = new Draggable('highlight_box');*/
			Event.observe($('main_image'), 'mousemove', enlargeSection, false);
			/* initialize the highlighter */
			tmp = $('main_image').down().cumulativeOffset();
			/* image dimensions - make it generic detect it by script, be careful with the embed object! */
			// mainImagePos = tmp;
			// mainImagePos = [55, 85];
			mainImageDims[0] = $('main_image').getWidth();
			mainImageDims[1] = $('main_image').getHeight();

			/* attacht events */
			// Event.observe($('highlight_box'), 'mousemove', enlargeSection, false);
			// Event.observe($('highlight_box'), 'mouseout', switchOffHighlightTimed, true);
			Event.observe($('main_image'), 'mouseout', switchOffHighlightTimed, true);
			
		//this should be re-factored as it is not always the case the first image in the list being the current image
		//search engine indexed pages will fail!!! on this
		
		if (gup('embed', $('thumbnail_list_wrapper').down(1).href) == 'true') {
			show_enlarged_image = false;  //disable the large image
			//replace the copy of the element to: click the play button to watch the video
			instructionBox(config.message_video, true); //$('see_enlarged').removeClassName('inactive');
		} else {	
				if (config.loadImage == false) {
					var src = $('thumbnail_list_wrapper').down(1).href;
				} else {
					var src = config.loadImage;
					config.loadImage = false;  //do it on load only
				}
				$('main_image_img').src = gup('main_image', src);

				if (gup('enlarged_image', src)) {
					$('enlarged_image_img').src = gup('enlarged_image', src);
					show_enlarged_image = true;
					instructionBox(config.message_image, true);  //$('see_enlarged').removeClassName('inactive');
				} else {
					show_enlarged_image = false;  //disable the large image
					instructionBox(config.message_image, false);  //$('see_enlarged').addClassName('inactive');
				}
			}
}


function buildSlider(){
	var insert_el = Builder.node('div', [
					Builder.node('div', {id: 'slider'}, [
						Builder.node('div', {id: 's_arrow_left'}, [
							Builder.node('img', {src: config.image_base + 'images/elements/s_arrow_left.gif', alt: 'Arrow left', width: 22, height: 23})
						]),
						Builder.node('div', {id: 's_body'}, [
							Builder.node('div', {id: 's_handle'})
						]),
						Builder.node('div', {id: 's_arrow_right'}, [
							Builder.node('img', {src: config.image_base + 'images/elements/s_arrow_right.gif', alt: 'Arrow right', width: 22, height: 23})
						])
					])
				]);
	Element.insert('thumbnailer', insert_el);
	
	//don't bother supporting PNG on IE6
	if (!config.browserIE){
		insert_el = Builder.node('img', {src: config.image_base + 'images/elements/s_right_edge.png', width: '22', height: '76', 'class':'right_trans_corner'});
		Element.insert('thumbnailer', { 'top': insert_el});
		insert_el = Builder.node('img', {src: config.image_base + 'images/elements/s_left_edge.png', width: '22', height: '76', 'class':'left_trans_corner'});
		Element.insert('thumbnailer', { 'top': insert_el});
	}

	Event.observe($('s_arrow_left').down(), 'mouseover', replaceImage, false);
	Event.observe($('s_arrow_left').down(), 'mouseout', replaceImage, false);
	Event.observe($('s_arrow_left').down(), 'click', clickPreviousScroll, false);

	Event.observe($('s_arrow_right').down(), 'mouseover', replaceImage, false);
	Event.observe($('s_arrow_right').down(), 'mouseout', replaceImage, false);
	Event.observe($('s_arrow_right').down(), 'click', clickNextScroll, false);

	sliderThumb = new Control.Slider('s_handle', 's_body', {
		range: $R(0, 100),
		/*values: [0, 50, 100],*/
		sliderValue: 0, // won't work if set to 0 due to a bug(?) in script.aculo.us
		onSlide: function(v){ 
            updateScrolling(v);
            currentSliderPosition = v;
	    },
		onChange: function(v){ 
		    updateScrolling(v);
		    currentSliderPosition = v;
	    }
	});
}
function switchOffHighlightTimed(e){
	if (show_enlarged_image == false){ 
		return;
	}
	clearTimeout(timer);  //clear previous timer if exists
	timer = setTimeout('switchOffHighlight()', 200); //set delay on the action 
	Event.stop(e);
}
function switchOffHighlight(){
	clearTimeout(timer);
	new Effect.Opacity($('highlight_box'), {duration: 0.5, from: 0.4, to: 0, queue: {scope: 'switchOffElement'}, afterFinish: function() {

	}});
	$('enlarged_image').hide();
	$('artwork_info').show();
}

function enlargeSection(e){
	//img = Event.findElement(e, 'img');
	if (show_enlarged_image == true){ 
		$('enlarged_image').show();
		$('artwork_info').hide();
	} else {
		return;
	}

	clearTimeout(timer);  //just in case the timeout is running
	
	mouse_x = Event.pointerX(e),
	mouse_y = Event.pointerY(e);

	//$('debug').innerHTML = highlightWidth + ':' + highlightHeight;
	$('highlight_box').show();
	new Effect.Opacity($('highlight_box'), {duration: 0, from: 0, to: 0.4, afterFinish: function() {}});
	updateHighlight(mouse_x, mouse_y);
	//updateEnlarged(mouse_x, mouse_y);
	Event.stop(e);
}
function updateEnlarged(mouse_x, mouse_y){
	new_top = (mouse_y - config.highlight_height/2 );
    new_left = (mouse_x - config.highlight_width/2);
	if ($('enlarged_image_img').src == 'none'){
		//nothing
	} else {
		$('enlarged_image').down(1).setStyle({
			marginLeft: '-' + new_left + 'px',
			marginTop: '-' + new_top + 'px'
		});
	}
}

function updateHighlight(mouse_x, mouse_y){
    //mainImageDims		
    //mainImagePos
    borderCorrection = 14;
    new_top = (mouse_y - config.highlight_height/2 );
    new_left = (mouse_x - config.highlight_width/2);
		
    if ((mouse_x - config.highlight_width/2) < mainImagePos[0]) {
        new_left = mainImagePos[0];
		// new_large_left = 0;
    }
    if ((mouse_x) > (mainImagePos[0] + mainImageDims[0] - config.highlight_width/2 - borderCorrection)) {
        new_left = mainImagePos[0] + mainImageDims[0] - config.highlight_width - borderCorrection;
		// new_large_left = mainImageDims[0]*enlarge_index;
    }
    if ((mouse_y - config.highlight_height/2) < mainImagePos[1]) {
        new_top = mainImagePos[1];
		// new_large_top = 0;
    }
    if ((mouse_y) > (mainImagePos[1] + mainImageDims[1] - config.highlight_height/2 - borderCorrection)) {
        new_top = mainImagePos[1] + mainImageDims[1] - config.highlight_height - borderCorrection;
		// new_large_top = mainImageDims[1]*enlarge_index;
    }
	
	new_large_left = (new_left - mainImagePos[0])*enlarge_index;
	new_large_top = (new_top - mainImagePos[1])*enlarge_index;
	
	$('highlight_box').setStyle({'top': new_top + 1  + 'px', 'left': new_left + 1 + 'px'});

	if (show_enlarged_image !== false ){
		// $('see_enlarged').removeClassName('inactive');
		$('enlarged_image').down(1).setStyle({
			marginLeft: '-' + new_large_left + 'px',
			marginTop: '-' + new_large_top + 'px'
		});
	} else {
		// $('see_enlarged').addClassName('inactive');
	}
	//$('debug').innerHTML = new_top;
}
//content_id - where to place the content
function requestContent(url, content_id, update_content){
		update_content = typeof(update_content) == 'undefined' ? false : update_content;
		new Ajax.Request(url,
		{
		    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
			method: 'get',
			parameters: {'ajax': 'true'},
			onSuccess: function(response_html){
                var response = response_html.responseText || "Panic! No response from the server!";
                if (content_id) {
					$(content_id).innerHTML = '';
					$('temp').innerHTML = response;
                }

                return false;
                			
			},
				
			onFailure: function(){ 
			    $(content_id).innerHTML = 'Panic! Unable to retrieve the source data! '+ url;
				return false;
			},
			onComplete: function(){
				$(content_id).innerHTML = $('temp').innerHTML;
				$('temp').innerHTML = '';
                $(content_id).cleanWhitespace();
				if (update_content == true){  //updated content?
					doStuff(content_id, url);
				}
			}
		});
		
		return false;

}

function mainObjectUpdate(e){
	link = Event.findElement(e, 'a');
	if ($('highlight_box')) $('highlight_box').remove();
	requestContent(link.href + config.update_params, 'artwork_info');
	show_enlarged_image = false;  //disable the large image
	//update the copy inside
	//$('see_enlarged').removeClassName('inactive');
	instructionBox(config.message_video, true); 
	$('main_image').innerHTML = ' ';  //remove the remains of original inside element
	requestContent(link.href + config.request_embed_params, 'main_image');
	Event.stop(e);
}

function mainImageUpdate(e) {
	link = Event.findElement(e, 'a');
	requestContent(link.href + config.update_params, 'artwork_info');
	if (!$('highlight_box')){
		createHighlightBox();
	}
	if (gup('enlarged_image', link.href)) {
		$('enlarged_image_img').src = gup('enlarged_image', link.href);
		show_enlarged_image = true;
		//$('see_enlarged').removeClassName('inactive');
		instructionBox(config.message_image, true); 
	} else {
		show_enlarged_image = false;  //disable the large image
		//$('see_enlarged').addClassName('inactive');
		instructionBox(config.message_image, false); 
	}
	
	if (gup('main_image', link.href)) {
		if (!$('main_image_img')) {  //does the element exists?
			$('main_image').innerHTML = ' ';  //remove the remains of original inside element
			Element.insert('main_image', config.main_imageHTML);
			$('main_image').down().src = gup('main_image', link.href);
			$('main_image').down().alt = link.down().alt;
			$('main_image').down().title = link.down().title;
		} else {
			if (!Prototype.Browser.IE) { //not ideal but working...
				Event.stopObserving($('main_image_img'), 'load', showLoadedImage, false);
			}
			new Effect.Opacity('main_image_img', {duration: config.effect_duration, from: 1.0, to: 0, queue: {scope: 'image_trans', limit: 1}, afterFinish: function() {
				$('main_image').down().src = gup('main_image', link.href);
				$('main_image').down().alt = link.down().alt;
				$('main_image').down().title = link.down().title;
				if (Prototype.Browser.IE) { //not ideal but working...
					$('main_image_img').onload = showLoadedImage;  //prototype doesn't handle this: weird
				} else {
					Event.observe($('main_image_img'), 'load', showLoadedImage, false); //make sure the images gets loaded first
				}
			}});
		}
	} else {
		//image not found - panic! do something - but what?
	}
	//$('main_image').down().href = gup('main_image', link.href);
	//ajax request content
	Event.stop(e);
}

function showLoadedImage(e){
	new Effect.Opacity('main_image_img', {duration: config.effect_duration, from: 0, to: 1.0, queue: {scope: 'image_trans', limit: 1}});
}

function linkBlurring(e) {
    var link = Event.element(e);
    if(link.blur) link.blur();
    Event.stop(e);
}


function browserDetect() {
    var ua = navigator.userAgent.toLowerCase();
    this.isIE = (ua.indexOf('msie') != -1);
	config.browserIE = false;
    if(this.isIE) {
    	config.browserIE = true;
        this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
        this.versionMajor = parseInt(this.versionMinor);
        //if(this.versionMajor == 5 || this.versionMajor == 6) fixPng = '.gif';
    }
}

function updateScrolling(v){
	cnst = 100 /($('thumbnail_list_wrapper').length-1);
    a = (gallery_pane_width-905)/905;
    $('thumbnail_list_wrapper').setStyle({
        left: '-' + a*v*9 + 'px'
    });
	//sliderThumb.setValue();
    //updateThumbnailsHighlite(Math.round(v/cnst));
}

function clickPreviousScroll(e) {
    //var elem = Event.findElement(e, 'div');
    if (currentSliderPosition > 10 ){
        currentSliderPosition = currentSliderPosition - 10;
    } else {
        currentSliderPosition = 0;
    }
    sliderThumb.setValue(currentSliderPosition);
    updateScrolling(currentSliderPosition);
    Event.stop(e);
}

function clickNextScroll(e) {
    //var elem = Event.findElement(e, 'div');
    if (currentSliderPosition < 90 ){
        currentSliderPosition = currentSliderPosition + 10;
    } else {
        currentSliderPosition = 100;
    }
    sliderThumb.setValue(currentSliderPosition);
    updateScrolling(currentSliderPosition);
    Event.stop(e);
}


function replaceImage(e){
	image = Event.findElement(e, 'img');
	image_str_pos = image.src.lastIndexOf('_on.gif');
	if (image_str_pos == -1) {
		image.src = image.src.slice(0, image.src.lastIndexOf('.gif')) + '_on.gif';
	} else {
		image.src = image.src.slice(0, image_str_pos) + '.gif';
	}
	Event.stop(e);
}
function showTitle(e){
	image = Event.findElement(e, 'img');
	if ($('portfolio_desc') && image.next('div')) {
		$('portfolio_desc').innerHTML = image.next('div').innerHTML; 
	}
	Event.stop(e);
}
//defining the rest of the class implementation
/*toggleMenu.prototype = {

  initialize: function(el_bg, el) {
    this.el_bg = el_bg;
    this.el = el;
    //assigning our method to the event

    this.el_bg.onmouseover = this.showMenuElement.bindAsEventListener(this);
    this.el.onmouseover = this.hideMenuElement.bindAsEventListener(this);
  },

  showMenuElement: function(evt) {
	Effect.BlindDown($('top_menu'), {duration: 0.5, queue: { position: 'front', scope: 'menu', limit: 1}, afterFinish: function() {
		}
	});
	Event.stop(evt);
  },

  hideMenuElement: function(evt) {
	if ($('top_menu').visible() == true){
		Effect.BlindUp($('top_menu'), {duration: 0.5, queue: { position: 'end', scope: 'menu', limit: 1}, afterFinish: function() {
	
			}
		});
	}
	Event.stop(evt);
	}

};*/

/* 
var toggleMenu = Class.create();
var watcher;
watcher = new testClass(i, 'Changed');

//defining the rest of the class implementation
toggleMenu.prototype = {

  initialize: function(el, message) {
    this.el = el;
    this.message = message;
    //assigning our method to the event

    this.el.onclick = this.showMessage.bindAsEventListener(this);
  },

  showMessage: function(evt) {
    var link = $(Event.findElement(evt, 'a'));  
    gID = gup('gID', link.href);
        
    fireFromLink = true;
    fireMouseEvent($(gID).down('a'));
    
    Event.stop(evt);
  }
};

*/

function gup(name, tmpURL) {
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    if (tmpURL) { //if is set - use it
       
    } else {
        var tmpURL = window.location.href;
    }
    var results = regex.exec(tmpURL);

    if (results == null) return false;
    else return results[1];
}

function createHighlightBox(){
	var insert_el = Builder.node('div', {id: 'highlight_box', style: 'display: none; width: ' + config.highlight_width + 'px; height: ' + config.highlight_height + 'px; '});
	Element.insert($('content'), insert_el);
	
	Event.observe($('highlight_box'), 'mousemove', enlargeSection, false);
	Event.observe($('highlight_box'), 'mouseout', switchOffHighlightTimed, true);
	
}

function instructionBox(message, show){
	if (!$('see_enlarged')) {
		var insert_el = Builder.node('div', {id: 'see_enlarged', className: 'inactive'});
		Element.insert($('thumbnailer'), {'before': insert_el});
	}
	var content = config.message_pre + message;
	$('see_enlarged').innerHTML = content;
	if (show) {
		$('see_enlarged').removeClassName('inactive');
	} else {
		$('see_enlarged').addClassName('inactive');
	}
}