/**
 * @author Bruno Bornsztein <bruno@missingmethod.com>
 * @copyright 2007 Curbly LLC
 * @package Glider
 * @license MIT
 * @url http://www.missingmethod.com/projects/glider/
 * @version 0.0.3
 * @dependencies prototype.js 1.5.1+, effects.js
 */

/*  Thanks to Andrew Dupont for refactoring help and code cleanup - http://andrewdupont.net/  */

Glider = Class.create();
Object.extend(Object.extend(Glider.prototype, Abstract.prototype), {
	initialize: function(wrapper, options){
	    this.scrolling  = false;
	    this.wrapper    = $(wrapper);
	    this.scroller   = this.wrapper.down('.scroller');
	    this.sections   = this.wrapper.getElementsBySelector('.sect');
	    this.options    = Object.extend({ duration: 1.0, frequency: 3 }, options || {});

	    this.sections.each( function(section, index) {
	      section._index = index;
	    });    

	    this.events = {
	      click: this.click.bind(this)
	    };

	    this.addObservers();
			if(this.options.initialSection) this.moveTo(this.options.initialSection, this.scroller, { duration:this.options.duration });  // initialSection should be the id of the section you want to show up on load
			if(this.options.autoGlide) this.start();
	  },
	
  addObservers: function() {
    var controls = this.wrapper.getElementsBySelector('.controls a');
    controls.invoke('observe', 'click', this.events.click);
  },	

  click: function(event) {
		this.stop();
    var element = Event.findElement(event, 'a');
    if (this.scrolling) this.scrolling.cancel();
    
    this.moveTo(element.href.split("#")[1], this.scroller, { duration:this.options.duration });     
    Event.stop(event);
  },

	moveTo: function(element, container, options){
			this.current = $(element);

			Position.prepare();
	    var containerOffset = Position.cumulativeOffset(container),
	     elementOffset = Position.cumulativeOffset($(element));

		  this.scrolling 	= new Effect.SmoothScroll(container, 
				{duration:options.duration, x:(elementOffset[0]-containerOffset[0]), y:(elementOffset[1]-containerOffset[1])});
		  return false;
		},
		
  next: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var nextIndex = (this.sections.length - 1 == currentIndex) ? 0 : currentIndex + 1;      
    } else var nextIndex = 1;

    this.moveTo(this.sections[nextIndex], this.scroller, { 
      duration: this.options.duration
    });
  },
	
  previous: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var prevIndex = (currentIndex == 0) ? this.sections.length - 1 : 
       currentIndex - 1;
    } else var prevIndex = this.sections.length - 1;
    
    this.moveTo(this.sections[prevIndex], this.scroller, { 
      duration: this.options.duration
    });
  },

	stop: function()
	{
		clearTimeout(this.timer);
	},
	
	start: function()
	{
		this.periodicallyUpdate();
	},
		
	periodicallyUpdate: function()
	{ 
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.next();
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency*1000);
	}

});

Effect.SmoothScroll = Class.create();
Object.extend(Object.extend(Effect.SmoothScroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }
   
    this.originalLeft=this.element.scrollLeft;
    this.originalTop=this.element.scrollTop;
   
    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } 
  },
  update: function(position) {   
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});Event.observe(window, 'load', initDesigns, false);

PAGE_LOAD = false;

function initDesigns() {
	PAGE_LOAD = true;
	if(LOADED_PAGE > 1 && window.location.href.indexOf("#s") < 0){
		window.location = window.location+'#s'+LOADED_PAGE;
	}
	var glide = new Glider('container',{duration:0.2});
	loadTheme($('theme'+LOADED_THEME).innerHTML);
	PAGE_LOAD = false;
}

function changePage(el) {
	$$('#page_buttons li').invoke('removeClassName', 'selected');
	el.addClassName('selected');
}

function changeTheme(id, el) {
	if(LOADED_THEME != id){
		LOADED_THEME = id;
		$$('#all_designs li').invoke('removeClassName', 'selected');
		$('theme_name').update(el.down().title);
		el.addClassName('selected');
		loadTheme($('theme'+id).innerHTML);
		changeDownloadURL();
	}
}

function changeDownloadURL(){
	$('dc').href="/gallery/designs/download/"+LOADED_THEME+"/";
	$('atw').href="/gallery/install/design/"+LOADED_THEME+"/";
	$('bkm').href="/gallery/designs/"+LOADED_THEME+"/";
}

function installTheme(){
	Lightbox.showUrl('/lightboxes/gallery-login.php', prepareLightbox);
}

function prepareLightbox(){
	$('theme').src="/gallery/install/design/"+LOADED_THEME+"/";
}

/*--------------------------------------
	BELOW HERE APPLIES CSS TO PREVIEW
----------------------------------------*/

var themeProperties = new Array("themeName",
					  "logoUrl",
					  "ftFormTitleFamily","ftFormTitleSize","ftFormTitleColor",
					  "ftFormDescriptionFamily","ftFormDescriptionSize","ftFormDescriptionColor",
					  "ftSectionTitleFamily","ftSectionTitleSize","ftSectionTitleColor",
				   	  "ftSectionTextFamily","ftSectionTextSize","ftSectionTextColor",
					  "ftFieldTitleFamily","ftFieldTitleSize","ftFieldTitleColor",
					  "ftFieldTextFamily","ftFieldTextSize","ftFieldTextColor",
					  "ftInstructFamily","ftInstructSize","ftInstructColor",
					  "bgHtmlColor","bgHtmlPattern",
					  "bgLogoColor","bgLogoPattern",
					  "bgFormColor",
					  "bgFieldColor",
					  "bgHighlightColor",
					  "bgInstructColor",
					  "brFormThickness","brFormStyle","brFormColor",
					  "brDividerThickness","brDividerStyle","brDividerColor",
					  "brInstructThickness","brInstructStyle","brInstructColor",
					  "dropShadow", "logoHeight");

function loadTheme(themeString){
	var themeArray = themeString.split(',');
	var tPLength = themeProperties.length;
	
	for(var i = 0; i < tPLength; i++) {
		var propertyName = themeProperties[i];
		var value = '';
		if(themeArray[i]){value = themeArray[i].replace(/^\s*|\s*$/g,"");}
		applyStyle(propertyName, value);
	}

}

function changeCSS(selector, property, value, container){
	(container != 'none')
		? 	selector = '#wallpaper ' + selector
		:	selector = selector;	
		
	cssElements = $$(selector);
	var dur = .2;
	if(PAGE_LOAD) dur = 0;
	for(var i=0; i<cssElements.length; i++) {
		var morphable = "height font-size color background background-color border-width border-color";
		if(morphable.match(property)){
			cssElements[i].morph(property+':'+value,{ duration: dur });
		}
		else{
			cssElements[i].style[property] = value;
		}
	}
}

function applyStyle(property, value){
	
	switch(property){
		//Logo
		case 'logoUrl': newValue = 'url('+value+')';
						changeCSS('a#logo','backgroundImage',newValue);
						if(browser == 'Internet Explorer 6' && $('logo').filters[0]){$('logo').filters[0].src = value}; break
		case 'logoHeight': if(value==''){value = 40;}
						   newValue = value + 'px';
						   changeCSS('a#logo','minHeight', 0);
						   changeCSS('a#logo','height', newValue); break

		//Drop Shadows
		case 'dropShadow': changeCSS('img#bottom2','visibility',value, 'none'); break
		
		//Backgrounds
		case 'bgHtmlColor': changeCSS('td#wallpaper','background-color',value, 'none'); break
		case 'bgHtmlPattern': changeCSS('td#wallpaper','background-image',value, 'none'); break
		case 'bgLogoColor': changeCSS('h1#nav2','background-color',value); break
		case 'bgLogoPattern': changeCSS('h1#nav2','background-image',value); break
		case 'bgFormColor': changeCSS('div#container2','background-color',value); break
		case 'bgFieldColor': changeCSS('input.text','background',value);
							 changeCSS('textarea.textarea','background',value); break
		case 'bgHighlightColor': changeCSS('li.focused','background',value); break
		case 'bgInstructColor': changeCSS('p.instruct','background-color',value); break

		//Borders
		case 'brFormThickness': changeCSS('div#container2','border-width',value); break
		case 'brFormStyle': changeCSS('div#container2','border-style',value); break
		case 'brFormColor': changeCSS('div#container2','border-color',value); break

		case 'brDividerThickness': changeCSS('div.info','border-width',value);
								   changeCSS('li.section','border-width',value); 
								   changeCSS('div.footer','border-width',value); break
		case 'brDividerStyle': changeCSS('div.info','borderBottomStyle',value); 
							   changeCSS('div.footer','borderTopStyle',value); break
		case 'brDividerColor': changeCSS('div.info','border-color',value);
							   changeCSS('li.section','border-color',value); 
							   changeCSS('div.footer','border-color',value); break

		case 'brInstructThickness': changeCSS('p.instruct','border-width',value); break
		case 'brInstructStyle': changeCSS('p.instruct','border-wtyle',value); break
		case 'brInstructColor': changeCSS('p.instruct','border-color',value); break
						
		//Typography
		case 'ftFormTitleFamily': changeCSS('div.info h2','font-family',value); break
		case 'ftFormTitleSize': changeCSS('div.info h2','font-size',value); break
		case 'ftFormTitleColor': changeCSS('div.info h2','color',value); break

		case 'ftFormDescriptionFamily': changeCSS('div.info div','font-family',value); break
		case 'ftFormDescriptionSize': changeCSS('div.info div','font-size',value); break
		case 'ftFormDescriptionColor': changeCSS('div.info div','color',value); break

		case 'ftSectionTitleFamily': changeCSS('li.section h3','font-family',value); break
		case 'ftSectionTitleSize': changeCSS('li.section h3','font-size',value); break
		case 'ftSectionTitleColor': changeCSS('li.section h3','color',value); break

		case 'ftSectionTextFamily': changeCSS('li.section div','font-family',value); break
		case 'ftSectionTextSize': changeCSS('li.section div','font-size',value); break
		case 'ftSectionTextColor': changeCSS('li.section div','color',value); break

		case 'ftFieldTitleFamily': changeCSS('label.desc','font-family',value); 
								   changeCSS('li div p','font-family',value); break
		case 'ftFieldTitleSize': changeCSS('label.desc','font-size',value); break
		case 'ftFieldTitleColor': changeCSS('label.desc','color',value);
								  changeCSS('li div p','color',value); break

		case 'ftFieldTextFamily': changeCSS('input.text','font-family',value); 
								  changeCSS('textarea.textarea','font-family',value); 
								  changeCSS('select.select','font-family',value);
								  changeCSS('label.choice','font-family',value); break
		case 'ftFieldTextSize': changeCSS('input.text','font-size',value); 
								changeCSS('textarea.textarea','font-size',value); 
								changeCSS('select.select','font-size',value); 
								changeCSS('label.choice','font-size',value); break
		case 'ftFieldTextColor': changeCSS('input.text','color',value); 
								 changeCSS('textarea.textarea','color',value); 
								 changeCSS('select.select','color',value); 
								 changeCSS('label.choice','color',value); break

		case 'ftInstructFamily': changeCSS('p.instruct','font-family',value); break
		case 'ftInstructSize': changeCSS('p.instruct','font-size',value); break
		case 'ftInstructColor': changeCSS('p.instruct','color',value); break
	}
}
