/**
 * @author Nathan Kelly - http://www.nathan-kelly.com/
 *  my email address is my first name @nathan-kelly.com
 * @copyright 2009 Australian Aluminium Finishing, all rights reserved
 * @package aaf-colour-selector
 * @version 4.0.8
 * @url http://www.aafonline.com.au/
 * @dependencies 
 * 	prototype.js 1.6.0.2+ (http://www.prototypejs.org/)
 *	scriptaculous.js 1.8.1+ (http://script.aculo.us/)
 */
var aaf_colour_selector = Class.create({
	
	_popupWidth: 480,
	_popupHeight: 768,
	
	initialize: function() {		
		
		this._preparePopupTriggers();
		
		if ( $('colour-selector-b') || $('colour-selector-c') ) {

			$('cs-filters').scrollTo();
			
		}

		if ( $('cs-filters') ) { 
		
			$$('.cs-panel').each(function(e){ $(e).className.match(/cs-selected/) ? $(e).show() : $(e).hide(); });
		
			if ( $('cs-tab-c').className.match(/cs-selected/) ) {
				
				$('cs-controls').hide();
				$('cs-panel-e').hide();
				$('cs-panel-e').removeClassName('cs-selected');
				$('cs-obsolete-colours').disabled = true;
				$('cs-detailed-results').disabled = true;
				
				
			} else {
				
				$('cs-controls').show();
				$('cs-panel-e').show();
				$('cs-panel-e').addClassName('cs-selected');
				$('cs-obsolete-colours').disabled = false;
				$('cs-detailed-results').disabled = false;
				
			}
			
			$$('input[type=checkbox]').findAll(function(c){ !$(c).up(('.cs-selected') ) ? $(c).disabled = true : $(c).disabled = false; });
			
			$$('select').findAll(function(s){ !$(s).up(('.cs-selected') ) ? $(s).disabled = true : $(s).disabled = false; });
			
		}
		
		document.observe('click', ( function(e){
			
			var target = Event.findElement(e, 'a[class^=cs-tab]') ||
			Event.findElement(e, 'input[class^=cs-select-all]') ||
			Event.findElement(e, 'li[class^=colour-swatch]') ||
			Event.findElement(e, 'area[class^=colour-map]') ||
			Event.findElement(e, 'a[class^=ui-sprite-icon]') ||
			Event.findElement(e, 'input[class^=ui-button]') ||
			Event.findElement(e, 'a[class^=ui-button]') ||
			Event.findElement(e, 'label[class^=children-invert]');
			
			if (target) {
				
				this._respond(target, e);
				
			}
			
		}).bindAsEventListener(this));
		
	},
	
	_respond: function( target, event ) {
		
		var a = target.id.split('-');
		
		if ( target.className.match(/cs-tab/) ) {			
			
			Event.stop(event);
			
			$$('.cs-tab').invoke('removeClassName', 'cs-selected');
			
			target.addClassName('cs-selected');
			
			$$('.cs-panel').invoke('removeClassName', 'cs-selected').invoke('hide');

			$$('#cs-panel-' + a[2]).invoke('addClassName', 'cs-selected').invoke('show');
			
			$$('input[type=checkbox]').findAll(function(c){ !$(c).up(('#cs-panel-' + a[2]) ) ? $(c).disabled = true : $(c).disabled = false; });
			
			$$('.cs-select-panel').findAll(function(c){ !$(c).up(('#cs-panel-' + a[2]) ) ? $(c).disabled = true : $(c).disabled = false; });
				
			$$('select', 'option').findAll(function(s){ !$(s).up(('#cs-panel-' + a[2]) ) ? $(s).disabled = true : $(s).disabled = false; });
			
			if ( target.id == 'cs-tab-c' ) {
				
				$('cs-controls').hide();
				$('cs-panel-e').hide();
				$('cs-panel-e').removeClassName('cs-selected');
				$('cs-obsolete-colours').disabled = true;
				$('cs-detailed-results').disabled = true;
				
			} else {
				
				$('cs-controls').show();
				$('cs-panel-e').show();
				$('cs-panel-e').addClassName('cs-selected');
				$('cs-obsolete-colours').disabled = false;
				$('cs-detailed-results').disabled = false;
				
			}
			
		} else if ( target.className.match(/cs-select-all/) ) {
			
			var parent = target.up('div');
			
			var selector = parent.down('select');

			var options = $$('option').findAll( function (o) { return o.descendantOf(selector); });
			
			options.each( function(o) {
				
				target.checked == true ? $(o).selected = true : $(o).selected = false;
				
			});
			
		} else if ( target.className.match(/colour-map/) ) {
			
			Event.stop(event);
			
			new Effect.Fade( 'colour-map-image', {
				from: 1.0,
				to: 0.5,
				duration: 0.2
			});

			this._runFilters( target, event );
			
			Event.observe( window, 'beforeunload', ( function(e) {
				
				new Effect.Fade( 'colour-map-image', {
					from: 0.5,
					to: 1.0,
					duration: 0
				});
				
			}).bindAsEventListener(this));
			
		} else if ( target.className.match(/colour-swatch/) ) {
			
			Event.stop(event);
			
			new Effect.Fade( 'colour-selector-b', {
				from: 1.0,
				to: 0.5,
				duration: 0.2
			});
			
			this._runFilters( target, event );
			
			Event.observe( window, 'beforeunload', ( function(e) {
				
				new Effect.Fade( 'colour-selector-b', {
					from: 0.5,
					to: 1.0,
					duration: 0
				});
				
			}).bindAsEventListener(this));
			
		} else if ( target.id == 'cs-search-button' || target.id == 'cs-browse-button' || target.id == 'cs-browse-filters-button' ) {
			
			Event.stop(event);
			
			if ( target.id == 'cs-search-button' ) {
				
				var filterURL = $('cs-search-location').value + '/(cs)/3/(search)/' + $('colour-search-text').value;
				
				window.location = filterURL;
				
			} else if ( target.id == 'cs-browse-button' ) {
				
				var filterURL = $('cs-search-location').value + '/(cs)/3';
			
				for ( var i = 0; i < $$('.cs-select-finish').length; i++ ) {
					
					if ( $$('.cs-select-finish')[i].selected && $$('.cs-select-finish')[i].disabled == false ) {
						
						filterURL += '/(ft)/' + $$('.cs-select-finish')[i].value;
						
					}
					
				}
				
				window.location = filterURL;
				
			} else {
				
				this._runFilters( target, event );
				
			}
			
		} else if (target.className.match(/uis-invert/) || target.className.match(/children-invert/)) {
			
			Event.stop(event);
			
			target.className.match(/selected/) ? target.removeClassName('selected') : target.addClassName('selected');
			
			var inputClass = 'input-' + a[1] + '-' + a[2];
			
			if (target.className.match(/uis-invert/)) {
				
				$$('.' + inputClass).each(function(e) {
					
					target.className.match(/selected/) ? $(e).checked = true : $(e).checked = false;
					
					target.className.match(/selected/) ? $($(e).parentNode).addClassName('checked') : $($(e).parentNode).removeClassName('checked');
					
					var b = $($(e).parentNode).id != '' ? $($(e).parentNode).id.split('-') : false;
					
					if ( b ) {
						
						var childClass = 'input-' + b[1] + '-' + b[2];
						
						$$('.' + childClass).each(function(c) {
							
							if ($(c).checked == true && $(e).checked == false) {
								
								$(c).checked = false;
								
							} else {
								
								$(c).checked = true;
								
							}
							
							$(c).checked == true ? $($(c).parentNode).addClassName('checked') : $($(c).parentNode).removeClassName('checked');
							
						});
						
					}
					
				});	
				
			} else {	
				
				Event.stop(event);
				
				var targetInput = target.down('input');
				
				$(targetInput).checked == true ? $(targetInput).checked = false : $(targetInput).checked = true;
				
				$(targetInput).checked == true ? $($(targetInput).parentNode).addClassName('checked') : $($(targetInput).parentNode).removeClassName('checked');
				
				$$('.' + inputClass).each(function(e) {
					
					if ($(e).checked == true && $(targetInput).checked == false ) {
						
						$(e).checked = false;
						
					} else {
						
						$(e).checked = true;
						
					}
					
					$(e).checked == true ? $($(e).parentNode).addClassName('checked') : $($(e).parentNode).removeClassName('checked');
					
				});
				
			}

		} else if (target.className.match(/uib-reset-selections/)) {
			
			Event.stop(event);
			
			$$('input[type=checkbox]').each(function(e) { $(e).checked = false; });
			
			$$('option').each(function(s) { $(s).selected = false; });
			
			if ( $('colour-selector-b') ) {
				
				$('colour-selector-b').hide();
				
			}
			
			if ( $('colour-selector-c') && $$('.class-colour-products') ) {
				
				$$('.class-colour-products')[0].hide();
				
			}
			
			if ( $$('.cs-colorbond-note') ) {
				
					$$('.cs-colorbond-note')[0].hide();
					
			}

		} else if (target == $('print-button')) {
			
			Event.stop(event);
			
			window.print();
			
		} else if (target == $('print-detail-button') || target == $('print-spec-button' )) {
			
			Event.stop(event);
			
			if ($('general-spec')) {
				
				// I'll have to hide a bunch of stuff here
				
				$('container').addClassName('printing-spec');
				
			} else if ($('column-1') && $('column-2')) {
				
				target == $('print-detail-button') ? $('column-2').addClassName('hidden') : $('column-1').addClassName('hidden');
				
				target == $('print-detail-button') ? $('column-1').removeClassName('hidden') : $('column-2').removeClassName('hidden');
				
			}
			
			window.print();
			
		} else if (target == $('save-button')) {
			
			Event.stop(event);
			
			// do nothing here
			
		}
		
	},
	
	_runFilters: function( target, event ) {
		
		var filterURL = '';
		
		
		if ( target.id == 'cs-browse-filters-button' ) {
			
			filterURL += '/(cg)/all';
			
		}
		
		// set the active panel
		
		$$('.cs-select-panel').each( function(e) {
			
				$(e).disabled == false ? filterURL += '/(cs)/' + $(e).value : '';
				
		});
		
		// end active panel
		
		var ag = [];
		
		for ( var i = 0; i < $$('.cs-all-grades').length; i++ ) {
			
			if ( $$('.cs-all-grades')[i].checked == true && $$('.cs-all-grades')[i].disabled == false ) {
			
					ag.push($$('.cs-all-grades')[i].value);
			}
		}
		
		if ( ag.length > 0 && ag.length != $$('.cs-all-grades').length ) {			
			
			filterURL += '/(ag)/';
			
			for ( var i = 0; i < ag.length; i++ ) {
				
				filterURL += ag[i];
				
				if ( i < ( ag.length - 1 ) ) {
					
					filterURL += '_';	
					
				}
				
			}
			
		}
		
		var am = [];
		var amAll = true;
		
		for ( var i = 0; i < $$('.cs-all-mans').length; i++ ) {
			
			if ( $$('.cs-all-mans')[i].checked == true && $$('.cs-all-mans')[i].disabled == false ) {
			
					am.push($$('.cs-all-mans')[i].value);
			}
		}
		
		if ( am.length > 0 && am.length != $$('.cs-all-mans').length ) {			
			
			amAll = false;
			
			filterURL += '/(am)/';
			
			for ( var i = 0; i < am.length; i++ ) {
				
				filterURL += am[i];
				
				if ( i < ( am.length - 1 ) ) {
					
					filterURL += '_';	
					
				}
				
			}
			
		}
				
		var f = [];
		var fAll = true;
		
		for( var i = 0; i < $$('.cs-finish-brands').length; i++ ) {
			
			if ( $$('.cs-finish-brands')[i].selected == true && $$('.cs-finish-brands')[i].disabled == false ) {
				
				f.push($$('.cs-finish-brands')[i].value);
				
			}
			
		}
		
		// if all are selected we don't need to do anything here because the default behaviour is all
		
		if ( f.length > 0 && f.length != $$('.cs-finish-brands').length ) {			
			
			fAll = false;
			
			filterURL += '/(fb)/';
			
			for ( var i = 0; i < f.length; i++ ) {
				
				filterURL += f[i];
				
				if ( i < ( f.length - 1 ) ) {
					
					filterURL += '_';	
					
				}
				
			}
			
		}
		
		if( $('cs-obsolete-colours').checked == true && $('cs-obsolete-colours').disabled == false ) {
			filterURL += '/(oc)/1';
		}
		
		if( $('cs-detailed-results').checked == true && $('cs-detailed-results').disabled == false ) {
			
			if ( !target.className.match(/colour-swatch/) ) {
				
				filterURL += '/(dr)/1';
				
			}
		}
		
		if ( target.id != 'cs-browse-filters-button' ) {
			
			var tref = target.href ? target.href : target.down('a').href;
			
		}else {
			
			// if user clicks the search button without making selections send to browse
			if ( amAll === true && fAll === true ) {
				
				filterURL = '';
				
				filterURL += '/(cs)/3/(ft)/0';
				
			}
		
			var tref = $('cs-search-location').value;
			
		}
		
		window.location = tref + filterURL;
		
	},
	
	_preparePopupTriggers: function() {
		
		if ( $('colour-selector-c') || $('spec-manager-b') ) {
			
			for (var i = 0; i < $$('.colour-product').length; i++ ) {
				
				var prod = $$('.colour-product')[i];
				
				var link = prod.down('a');
				
				var path = link.href;
				
				var text = link.innerHTML;
				
				link.replace('<strong>' + text + '</strong>');
				
				this._openWindow(prod, path);
				
			}
			
		}
		
		if ($('basket-count')) {
			
			var elm = window.opener.document.getElementById('sample-basket-count');
			
			if ( document.getElementById('basket-count') ) {
				
				var count = document.getElementById('basket-count').value;
			
				if ( elm ) {
					
					// use the old skool method because its not a big deal for this
					elm.innerHTML = count;
					
				} else {

					var bid = window.opener.document.getElementById('basket-info');
					
					if ( bid ) {
						
						// use the old skool method because its not a big deal for this
						bid.innerHTML = '<div class="sample-basket-summary"><ul><li><a href="/dispatch/basket">Sample Basket</a> (<span id="sample-basket-count">' + count + '</span>)</li></ul></div>';

					}
				}
				
			}
		}
		
	},
	
	_openWindow: function(prod, path) {
		
		Element.observe(prod, 'click', (function(e) {			
			
			var win = prod.id.split('-');
			
			var wd = document.viewport.getDimensions();
			
			var popx = (wd.width - this._popupWidth) * 0.5;
			
			var popy = (wd.height - this._popupHeight) * 0.5;
			
			window.open(path,win[2],'width='+this._popupWidth+',height='+this._popupHeight+',top='+popy+',left='+popx+',menubar=0,location=0,toolbar=0,personalbar=0,status=0,scrollbars=1,allowresize=1,dependent=1');
			
			Event.stop(e);
			
		}).bindAsEventListener(this));
		
	}
	
});

document.observe('dom:loaded', function () { new aaf_colour_selector(); });
