﻿var toggleMenu = Class.create();
var watcher;
var domain = 'ayanambu.com';
var browserIE = false; //indicate IE
/* Slider variables */
var currentSliderPosition = 0;
var gallery_pane_width = 0;
/* END: slider variables */




var deltaX = 400;
var deltaY = 100;
var boxWidth = 100;
var boxHeight = 100;
var magnification = 3;
        
Event.observe(window, 'load', init, false);
  
function init(){
	browserDetect();
//	$('top_menu').toggleClassName('hidden_menu');
	$('top_menu').hide();
	watcher = new toggleMenu($('top_menu_bg'), $('content'));
	$A(document.getElementsByTagName('a')).each(function(i){
		Event.observe(i, 'focus', linkBlurring, false);
	});
/*    
    var cookieVal = readCookie('Mazda6_HTML');
   
    if (cookieVal == 'true'){
        //HTML version is the user's decission
    }
    if (cookieVal == 'false') {
        //either coming from the flash site or search engine
        document.getElementById('link_go_to_flash').style.display = 'none';
        if (document.getElementById('link_home_flash').innerHTML) { document.getElementById('link_home').innerHTML = document.getElementById('link_home_flash').innerHTML; }
    }
    if (cookieVal == null) {
        document.location = redirectPage + '?originalURL=' + window.location;
    }
*/
	if ($('image_list')) {
		$A($('image_list').getElementsByTagName('li')).each(function(i, cnt) {
			Event.observe(i, 'mouseover', showTitle, false);
		});
	}
	if ($('aya_email')){
		$('aya_email').replace('<a href="mailto:' + 'Aya@' + domain + '">Aya@' + domain + '</a>');
	}
	if ($('window')) {
		//new Effect.HighlightText('window');
		//$('window').hide();
		//new Effect.BlindRight($('window'), { afterFinish: function(){
		//	new Effect.BlindLeft($('window'));
		//}});  //shows the div
		//Effects.BlindLeft($('someDivId'));  //hides the div
		//Effect.Gravity.up('window', deltaX, deltaY, boxWidth, boxHeight, magnification);
		//$('window').hide(); //this will be done by AJAX just before displaying it
		//Effect.BlindDown($('window'), {duration: 1});
	}
	if ($('slider')){
		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);
		//$A($('thumbnail_list').getElementsByTagName('a')).each(function(i){
	    //    gallery_pane_width += i.getWidth() + 6; /* compensate margin */
	    //});
	    gallery_pane_width = $A($('thumbnail_list').getElementsByTagName('a')).length * 109;
	    gallery_pane_width += 2;
		//gallery_pane_width += 84; //correction
		//gallery_pane_width += 42; //correction
	    $('thumbnail_list').setStyle({
	        width: gallery_pane_width + 'px'
	    });
	    $A($('thumbnail_list').getElementsByTagName('a')).each(function(i){
	    	Event.observe(i, 'click', mainImageUpdate, 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;
		    }
		});
		
	}
//portfolio_desc
}

//content_id - where to place the content
function requestContent(url, content_id){

		new Ajax.Request(url,
		{
		    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
			method: 'get',
			onSuccess: function(response_html){
                var response = response_html.responseText || "no response";
                if (content_id) {
                $(content_id).innerHTML = response;
                $(content_id).cleanWhitespace();
                }

                return false;
                			
			},
				
			onFailure: function(){ 
			    alert('Unable to retrieve the source data! '+ url );
				return false;
			},
			onComplete: function(){
			}
		});
		
		return false;

}


function mainImageUpdate(e) {
	link = Event.findElement(e, 'a');
	requestContent(link.href, 'artwork_info');

	if (gup('main_image', link.href)) {
		new Effect.Opacity('main_image_img', {duration: 1, 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;
			new Effect.Opacity('main_image_img', {duration: 1, from: 0, to: 1.0, queue: {scope: 'image_trans', limit: 1}});
		}});
	} else {
		//image not found
	}
	//$('main_image').down().href = gup('main_image', link.href);
	//ajax request content
	Event.stop(e);
	return false;
}

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);
	browserIE = false;
    if(this.isIE) {
    	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').length-1);
    a = (gallery_pane_width-905)/905;
    $('thumbnail_list').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')) {
		if (image.alt ) { $('portfolio_desc').innerHTML = image.alt; }
	}
	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);
  }
};

*/
//sourced at: http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

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];
}


        Effect.Transitions.exponential = function(pos) {
            return 1-Math.pow(1-pos,2);
        }
        Effect.Transitions.exponentialReverse = function(pos) {
            return Math.pow(pos,2);
        }
        Effect.Gravity = {
            up:function(divId, distX, distY, boxWidth, boxHeight, magnification) {
                var parallel = new Effect.Parallel(
                    [
                        new Effect.Move(divId, { x: distX/2 - boxWidth*(magnification-1)/2, y: distY/2 - boxHeight*(magnification-1)/2, mode: 'relative', transition: Effect.Transitions.exponential})
                        ,
                        new Effect.Scale(divId, magnification * 100.0, { transition: Effect.Transitions.exponential })
                    ],
                    Object.extend({ 
                        divId: divId,
                        distX: distX,
                        distY: distY,
                        boxWidth: boxWidth,
                        boxHeight: boxHeight,
                        magnification: magnification,
                        afterFinishInternal: function(effect) {
                             Effect.Gravity.down(this.divId, this.distX, this.distY, this.boxWidth, this.boxHeight, this.magnification);
                        },
                        delay: 0.0,
                        duration: 0.5
                     })
                )
            },
            down:function(divId, distX, distY, boxWidth, boxHeight, magnification) {
                var parallel = new Effect.Parallel([
                    new Effect.Move(divId, { x: distX/2 + boxWidth*(magnification-1)/2, y: distY/2 + boxHeight*(magnification-1)/2, mode: 'relative', transition: Effect.Transitions.exponentialReverse})
                    ,
                    new Effect.Scale(divId, 100.0 / magnification, {transition: Effect.Transitions.exponentialReverse})
                ],
                    Object.extend({
                        delay: 0.0,
                        duration: 0.5
                    })
                )
            }
        };


Effect.HighlightText = Class.create();
Object.extend(Object.extend(Effect.HighlightText.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    if(this.element.getStyle('display')=='none') { this.cancel(); return; }

    if(!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('color').parseColor('#000000');
    if(!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('color');

    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({color: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle({color: this.options.restorecolor});
  }
});
