// JavaScript Document

var siteWidth = 825;
var siteHeight = 620;
var bottomOffset = 128;
var selCollection = 'none';

$(document).ready(function(){
	
	$.ajaxSetup({
		url: "_konstrukt/ajax.gateway.php",
		global: false
	});
	
	rebind();
	
	$('.submit').live('click', function() { return false; });
	$('.back').live('click', function() { history.go(-1);  return false; });
	$('.print').live('click', function() { window.print(); return false; });
	$('.redirector').live('click', function() { if ($(this).attr('url')) window.location.href = $(this).attr('url'); return false; });
	
	$('.rad').inputReplace('radio');
	$('.incrementer').inputReplace('incrementer');
	
	if (($(window).height()+bottomOffset) <= siteHeight) {
		$('#homeFeatures').css({'marginTop':($(window).height() - 198)});
	}
	
	preloadBG('images/industrie_bg_1.jpg');
	
	$('.catBtn').click(function(){
		/*
		if ($('#catalogue').hasClass('opened')) {
			$('#flash-layer').hide();
			flashRequest('divContract');
			$('#catalogue').removeClass('opened');
			$('#catalogue').stop().animate( {height:'35px'}, 500, "linear");
		} else {
			$('#catalogue').addClass('opened');
			$('#flash-video').hide();
			$('#catalogue').stop().animate( {height:'120px'}, 500, "linear", function(){
			});
		}
		*/
		$(this).blur();
        return false;
	});

	$('#catalogue ul li a').live('click', function() {
		//flashRequest('divContract');
		//flashRequest('collection');
		selCollection = $(this).attr('rel');
		
		if ($('#flash-layer').is(':visible')) {
			flashRequest('collection');
		} else {
			$('#flash-layer').show();
			doFlashPos('#flash-layer');
		}
		$(this).blur();
        return false;
	});
	
	$('.flash-video').click(function(){
		$('#flash-layer').hide();
		$('#flash-video').show();
		doFlashPos('#flash-video');
		$(this).blur();
        return false;
	});
	
	/*flowplayer("flowplayer", "flowplayer-3.1.0.swf", { 
		clip:  { 
			autoPlay: false, 
			autoBuffering: true
		} 
	});*/
	
	$('#scroller .item').hover( 
		function() { $(this).prepend('<div class="hover"></div>'); },
		function() { $('#scroller .item .hover').remove(); }
	);
	
	$(window).resize(function(){
		//$('#colOne').animate( {height:$(window).height()}, 500);
		doFlashPos('#flash-layer');
		doFlashPos('#flash-video');
	});
	
	$('#scroller .item').click(function() {
		
		var loadImage = 'images/catalogue/'+$(this).attr('image')+'.jpg';
		
		$('#catalogue #bar').stop().animate( {width:'0'}, 400, "linear", function(){
			
			$('#catalogue .link').removeClass('opened');
			
			$('#homeArea, #featuredProducts, .colTwo, .colThree').hide();
			$('#colOne').animate( {height:siteHeight}, 500);
			
			$('#preloader').show();
			
			var newLoad = $("<img />").addClass('hidden').attr('src',loadImage);
			$('#preloader').append(newLoad);
			
			$('#preloader img')
				.load(function() {
					//alert('Image Loaded');
					$('#over-layer').css('backgroundImage', 'url('+loadImage+')');
					$('#preloader img').remove();
					$('#preloader').fadeOut('slow', function(){
						if ($(window).height() <= siteHeight) {
							$('#featuredProducts').css({'marginTop':($(window).height() - 82)});
						}
						$('#featuredProducts').fadeIn('slow');
					});
					
				})
				.error(function () {
					alert('Error loading image. Try reloading this page.');
					/*$('#over-layer').css({'backgroundImage' : 'url(images/notfound.jpg)', 'backgroundPosition' : '50% 50%'});
					$('#preloader img').remove();
					$('#preloader').fadeOut('slow');*/
				});
		
		});
		
		$(this).blur();
        return false;
	});
	
	$('#scroller .item img')
		.load(function() {
		})
		.error(function () {
			$(this).prepend('<div class="preload"></div>').attr('src','images/notfound.jpg');
		});
		
	// menu expander
	$('.parent').live('click', function() {
		if (!$(this).next('.child').is(':animated')) {
			if ($(this).next('.child').hasClass('opened')) {
				$(this).next('.child').slideUp(200).removeClass('opened')
			} else {
				$('.child').removeClass('opened').slideUp(200);
				$(this).next('.child').slideDown(500).addClass('opened');
			}
		}
		$(this).blur();
        return false;
	});
	
	$('#products .item').live('click', function() {
		
		/*hash = window.location.href;
		alert(hash.replace(/^.*#/, ''));*/
		
		//window.location.hash = $(this).attr('hash');
		
		$('#products .item .selected').remove();
		$(this).prepend('<div class="selected"></div>');
		$.scrollTo('body', 500);
		$('.colThree').show('fast');
		
		$('#detailArea .image img').attr('src', $('img',this).attr('src'));
		$('#detailArea .price').html($('.price',this).html());
		$('#detailArea .title').html($('.title',this).html());
		
		rebind();
		
        return false;
	});
	
	$('#products .item').hover( 
		function() { $(this).prepend('<div class="hover"></div>'); },
		function() { $('#products .item .hover').remove(); }
	);
	
	
	$('div', '#storeCountries, #storeStates, #storeCities').hover( 
		function() { $(this).addClass('hover'); },
		function() { $(this).removeClass('hover'); }
	);
	
	$('#storeCountries a').live('click', function() {
		var storeStates = '.c-'+$(this).attr('countryId');
		$('div','#storeCountries').removeClass('selected');
		$(this).closest('div').addClass('selected');
		$('div', '#storeStates, #storeCities, #storeLocations').hide('fast');
		$(storeStates, '#storeStates').show('fast');
		$(this).blur();
        return false;
	});
	
	$('#storeStates a').live('click', function() {
		var storeCities = '.s-'+$(this).attr('state');
		$('div','#storeStates').removeClass('selected');
		$(this).closest('div').addClass('selected');
		$('div', '#storeCities, #storeLocations').hide('fast');
		$(storeCities, '#storeCities').show('fast');
		$(this).blur();
        return false;
	});
	
	$('#storeCities a').live('click', function() {
		var storeLocations = '.c-'+$(this).attr('countryId')+'.s-'+$(this).attr('state')+'.t-'+$(this).attr('city');
		$('div','#storeCities').removeClass('selected');
		$(this).closest('div').addClass('selected');
		$('div', '#storeLocations').hide('fast');
		$(storeLocations, '#storeLocations').show('fast');
		$(this).blur();
        return false;
	});
	
	/*$('#storeLocations a').live('click', function() {
		$('div','#storeLocations').removeClass('selected');
		$(this).closest('div').addClass('selected');
		$('#googleMap', '#storeMap').hide();
		$('#googleMap', '#storeMap').show('fast');
        return false;
	});*/
	
});


function rebind() {
	
	$('.defuscate').defuscate();
	//$('.equal').equalHeights();
	//$('.quantityArea, .addToCartArea').equalHeights();
	
	$('.suggestion, #featuredProducts .item').qtip({
		content: {
			text: false // Use each elements title attribute
		},
		show: { delay: 100 },
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomMiddle'
			}
		},
		style: { 
			width: 150,
			fontSize: '10pt',
			lineHeight: '12pt',
			padding: 5,
			background: '#ffcc00',
			color: '#000',
			textAlign: 'center',
			border: {
				width: 3,
				color: '#ffcc00'
			},
			tip: 'bottomMiddle',
			name: 'dark' // Inherit the rest of the attributes from the preset dark style
		}
	});
	
}

function doFlashPos(flashDiv) {
	var flashPos = $('#colOne').offset();
	var flashLeft = flashPos.left+$('#colOne').width();
	var flashWidth = $(flashDiv).width();
	var screenWidth = $(window).width();
	var flashDiff = screenWidth - flashWidth - flashLeft;
	var newWidth = flashDiff + flashWidth;
	$(flashDiv).css('width',newWidth+'px');
}

function preloadBG(img) {
	
	//loadImage = 'images/catalogue/'+$(this).attr('image')+'.jpg';
	
	$('#preloader').show();
	
	var newLoad = $("<img />").addClass('hidden').attr('src',img);
	$('#preloader').append(newLoad);
	
	$('#preloader img')
		.load(function() {
			$('#over-layer').css('backgroundImage', 'url('+img+')');
			$('#preloader img').remove();
			$('#preloader').fadeOut('slow');
			
		})
		.error(function () {
			alert('Error loading image. Try reloading this page.');
		});
}

function flashRequest(func, obj) {
	
	//alert(func);
	
	//var obj = new Array(); eval("obj="+obj);
	
	switch (func) {
		
		case 'setBackground':
			if (obj.img) {
				$('#over-layer').css('backgroundImage', 'url('+obj.img+')');
			} else if (obj.colour) {
				$('#preloader').css({'backgroundImage': 'none', 'backgroundColor': obj.colour}).fadeIn('fast');
			} else {
				$('#preloader').fadeOut("fast", function(){$(this).css({'backgroundImage': 'url(images/loading.gif)', 'backgroundColor': 'none'});});
			}
			break;
		
		case 'divHeight':
			$('#flash-layer').css('height', obj+'px');
			break;
		
		case 'divExpand':
			$('#colTwo, #colThree').fadeOut('fast');
			$('#preloader').fadeIn('slow');
			$('#flash-layer').css('height', siteHeight+'px');
			break;
		
		case 'divContract':
			$('#preloader').fadeOut('slow');
			$('#colTwo, #colThree').fadeIn('fast');
			$('#flash-layer').css('height', '175px');
			break;
		
		case 'collection':
			//return selCollection;
			thisMovie("collection").flashRequest(selCollection);
			break;
			
		case 'debug':
			
			if (obj) {
				var echo = '';
				for (prop in obj) {
					if ('object' == typeof(obj[prop])) {
						for (subObj in obj[prop]) {
							echo += subObj + ": " + obj[prop][subObj] + "\n";
						}
					} else {
						echo += prop + ": " + obj[prop] + "\n";
					}
				}
				alert(echo);
			} else {
				alert('No Object!');
			}
			break;
			
		default:
			alert('Not a valid flash request!');
	}
	
	//sendToActionScript(func);
}
function thisMovie(movieName) {
	 if (navigator.appName.indexOf("Microsoft") != -1) {
		 return window[movieName];
	 } else {
		 return document[movieName];
	 }
 }
 function sendToActionScript(value) {
	 thisMovie("collection").sendToActionScript(value);
 }

/* Email Defuscator */
(function($){
	jQuery.fn.defuscate = function( settings ) {
		settings = jQuery.extend({
			link: true,
			find: /\b([A-Z0-9._%-]+)\([^)]+\)((?:[A-Z0-9-]+\.)+[A-Z]{2,6})\b/gi,
			replace: '$1@$2'
		}, settings);
		return this.each(function() {
			if ( $(this).is('a[@href]') ) {
				$(this).attr('href', $(this).attr('href').replace(settings.find, settings.replace));
				var is_link = true;
			}
			$(this).html($(this).html().replace(settings.find, (settings.link && !is_link ? '<a href="mailto:' + settings.replace + '">' + settings.replace + '</a>' : settings.replace)));
		});
	};
})(jQuery);


(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			$(this).height(tallest).css("overflow","auto");
		});
	}
})(jQuery);



/* radio replacement plugin */
(function($) {
	$.fn.inputReplace = function(e) {
		switch (e) {
			case 'radio':
				
				$(" + label", this)
					.each( function(){
						$(this).addClass($(this).prev().attr('class')+"_label");
						if ( $(this).prev()[0].disabled ) {
							if ( $(this).prev()[0].checked ) {
								$(this).addClass("checked_disabled");
							} else {
								$(this).addClass("disabled");
							}
						} else if ( $(this).prev()[0].checked ) {
							$(this).addClass("checked");
						}
					})
					.hover( 
						function() { $(this).addClass("over"); },
						function() { $(this).removeClass("over"); }
					)
					.click( function() {
						if ( !$(this).prev()[0].disabled ) {
							$("."+$(this).prev().attr('class')+"_label").removeClass("checked").removeClass("checked_disabled");
							$(this).addClass("checked");
							//$("input['"+$(this).prev().attr('name')+"']").checked = '';
							//$(this).prev()[0].checked = !$(this).prev()[0].checked;
						}
					})
					.prev().hide();
				break;
				
			case 'incrementer':
				
				$(this).before('<a href="#" class="minus button">-</a>');
				$(this).after('<a href="#" class="plus button">+</a>');
				
				$('.plus, .minus').live('click', function() {
					var quantity = $(this).closest('.quantityArea').find('input[name=quantity]').val();
					if ($(this).hasClass('plus') && quantity < 99) {
						quantity++;
					} else if ($(this).hasClass('minus') && quantity > 1) {
						quantity--;
					}
					$(this).closest('.quantityArea').find('input[name=quantity]').val(quantity)
					return false;
				});
				break;
		}
	}
})(jQuery);
