var spinnerImg = new Element('img', {
    'src': 'images/ajax-loader.gif'
});
var spinnerCode = "images/ajax-loader.gif";
var ie = false;

PreloadImages();

window.addEvent('domready', function(){
	// IE6 fix
	if ((Browser.Engine.trident) && (Browser.Engine.version<5)) {
		new Asset.css('css/ie6.css');
		ie = true;
	}

	// global rollovers 
	applyRollovers($$(".rollover"));
	
	// product selector 
	if ($('popup_container')) {
		enableProducts();
	}	
	
	// acc finder
	if ($('finderbrand')) {
		enableFinder();
	}		
	
	if ($('supportbrand')) {
		enableSupport();
	}		
	
	if($('slrproduct')) {
		enableSlr();		
	}

	// enable search events
	enableSearch();
});  
// end domready ==============================

// =============================FUNCTIONS ==============================
// enable product selector page
function enableProducts() {
	var popupPanel = $('popup_container');
	
	var productButtons = $$(".slider_b");
	productButtons.each(function(productButton, i) {
		// extract the ID
		var butId = productButton.get('id');
		butId = butId.substr(8, 1);
		productButton.butId = butId;
		
		// MANAGE THE EXTRA BUTTONS
		var extraButton = $("slider_x" + butId);
		var slideArea = $('slider_' + butId);		
		extraButton.set('href','#');
		extraButton.addEvent("click", function() {
			productButton.fireEvent("click");
			slideArea.setStyle('margin-left', '0px');	
		});
		// custom rollovers
		extraButton.addEvent("mouseenter", function() {
			slideArea.set('tween', {duration: 150, link: 'cancel'});
			slideArea.tween('margin-left', '20px');
		});		
		extraButton.addEvent("mouseleave", function() {
			slideArea.set('tween', {duration: 150, link: 'cancel'});
			slideArea.tween('margin-left', '0px');
		});				
		
		// remove hyperlink
		productButton.set('href','#');		
		// CLICK EVENT
		productButton.addEvent("click", function() {
			// reveal product details layer (in case it's the 1st time)
			popupPanel.setStyle('display','block');					
			// remove extra buttons (in case it's the 1st time)
			var extraButtons = $$(".slider_bt_extra");
			extraButtons.each(function(extraButton, i) {
				extraButton.destroy();
			});
			
			// remove any product details
			popupPanel.empty();
			
			// init variables
			var minX = -19;
			var currentX = 0;
			var targetX = 0;
			var widthX = 24;
			var widthOpen = 852;
			var currentPanel = null;
			var myTransition = new Fx.Transition(Fx.Transitions.Sine, 3);				
			
			// move all the sections
			for(i=1; i<7; i++) {
				// slide left or right
				if (i<=this.butId) {  targetX = minX + (widthX * i); }
				if (i>this.butId) {  targetX = minX + (widthX * i) + widthOpen; }
				currentPanel = $$('#slider_' + i);				

				// change width of the photograph container
				if(i==this.butId) {  // current button
					// photo grow
					var openPanel = currentPanel.getElement('.slider_bg');			
					var openImage = openPanel.getElement('img');
					openImage.set('tween', {duration: 500});					
					openImage.tween('left', '0px');
					// move popup window to correct position
					var newX = (widthX * this.butId);
					// correction of positioning 
					//if (this.butId == 1) { newX = 0; } else { newX = newX + 5; }
					popupPanel.setStyle('left', newX);
					popupPanel.set('category', this.butId);
					// load and fade in popup window slowly
					loadCategoryList.delay(250); 
				} 
				// move the panels
				this.setStyle('margin-left', '0px');
				currentPanel.set('tween', {duration: 'normal', transition: myTransition.easeOut});
				currentPanel.tween('left', targetX);			
			}
		});

	});
	// fire off event if required
	if(selcategory>0) {
		var clickedButton = $('slider_b' + selcategory);
		clickedButton.fireEvent('click');
	}
}

// enable finder forms
function enableFinder() {
	$('finderbrand').addEvent("change", function() {
		// load and show the list of models
		var selected = $('finderbrand').getSelected();
		var model = selected.getProperty('value');
		
		var urlPath = "lib/getcontent.php?type=findermodels&cat=" + model;
		
		var req = new Request.HTML({
			url:urlPath, 
			method:'get',		
			onSuccess: function(html) {	
				// display categories
				var wrapper = $('findermodelwrapper');	
				wrapper.empty();
				wrapper.adopt(html);
				$('model').addEvent("change", function() {
					$('searchwrapper').setStyle('display','block');	
				});
			}
		});
		req.send();		
	});
}

function finderFinal(category, model, catname) {
	var urlPath = "lib/getcontent.php?type=finderfinal&cat=" + category + "&prodid=" + model + "&page=" + catname;
	var req = new Request.HTML({
			url:urlPath, 
			method:'get',		
			onSuccess: function(html) {	
				// display categories
				var wrapper = $('finalfinder');	
				wrapper.empty();
				wrapper.adopt(html);
			}
		});
	req.send();
}

// enable support forms
function enableSupport() {
	$('supportbrand').addEvent("change", function() {
		// load and show the list of models
		var selected = $('supportbrand').getSelected();
		var model = selected.getProperty('value');
		
		var urlPath = "lib/getcontent.php?type=supportmodels&cat=" + model;
		
		var req = new Request.HTML({
			url:urlPath, 
			method:'get',		
			onSuccess: function(html) {	
				// display categories
				var wrapper = $('supportmodelwrapper');	
				wrapper.empty();
				wrapper.adopt(html);
				$('supportmodel').addEvent("change", function() {
					var selectedmodel = $('supportmodel').getSelected();
					var modelurl = selectedmodel.getProperty('value');
					window.location = modelurl;
				});
			}
		});
		req.send();		
	});
	
	$('feedbacknotice').fade('hide');
	
	$('submitfeedback').addEvent("click", function() {	
		// validation first
		$('feedbacknotice').fade('hide');
		var allFields = $$('.formfield');
		var data = "";
		var email = "";
		
		allFields.each(function(thisField,i) {
				if ((thisField.value).length<3) {
					thisField.addClass('highlight');
					$('feedbacknotice').fade('show');
					valid = 0;
				} else {
					thisField.removeClass('highlight');
				}
				var name = thisField.name;
				data += thisField.name + " = " + thisField.value + "<br>";
				if(thisField.name==email) { email=thisField.value; }
		})

		if ($('feedbacknotice').getStyle('opacity')==0) {
				// send email if ok
				var urlPath = "lib/getcontent.php?type=feedback&cat=" +data+"&page=" + email;
				
				var req = new Request.HTML({
					url:urlPath, 
					method:'get',		
					onSuccess: function(html) {	
						// display categories
						var wrapper = $('feedbackform');	
						wrapper.empty();
						wrapper.adopt(html);
					}
				});
				req.send();
		}
    });
}

// load and show content (Ajax)
function loadCategoryList() {
	var popupPanel = $('popup_container');
	var category = popupPanel.get('category');	
	popupPanel.empty();
	//popupPanel.grab(spinnerImg);
	
	var urlPath = "lib/getcontent.php?type=catlist&cat=" + category;

	// load category list
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',		
		onSuccess: function(html) {	
			// display categories
			var catList = new Element('div', {
			    'id': 'popup_catlist'
			});
			catList.adopt(html);
			// skip category listing if single category
			if(catList.get('html').indexOf("no_category")>-1) {
				// add punch line panel
				var punchPanel = new Element('div', {'id': 'popup_punch'});
				popupPanel.grab(punchPanel);
				// punchline
				var so = new SWFObject( "images/flash/" + category + ".swf", "Product image", "340", "430", "8");
				so.addParam("wmode", "transparent");
				so.write("popup_punch");
				// and skip to categories
				loadProductList(category);
			} else {
				popupPanel.empty();
				popupPanel.fade('hide');
				popupPanel.grab(catList);
				popupPanel.fade('in');
				// enable link highlight
				var allLinks = $$('#popup_catlist a');
				allLinks.each(function(thisLink, i) {
					thisLink.addEvent('click', function() {
						var allLinks = $$('#popup_catlist a');
							allLinks.each(function(thisLink, i) {
							thisLink.removeClass('selected');
					       });
						this.addClass('selected');							
					});
				});
				// enforce action if subcategory set
				if(selsubcategory>0) {
					loadProductList(selsubcategory);
				}
				// add punch line panel
				var punchPanel = new Element('div', {'id': 'popup_punch'});
				popupPanel.grab(punchPanel);
				var so = new SWFObject( "images/flash/" + category + ".swf", "Product image", "340", "430", "8");
				so.addParam("wmode", "transparent");
				so.write("popup_punch");
			}
		}
	});
	req.send();
	
}

function loadProductList(category) {
	var popupPanel = $('popup_container');

	// remove previous list if exists
	if ($('popup_prodlist')) {
		$('popup_prodlist').destroy();
	}
	if ($('popup_details')) {
		$('popup_details').destroy();
	}	

	// we can create the product list now as it's not optional
	var prodList = new Element('div', {
	    'id': 'popup_prodlist'
	});
	prodList.fade('hide');
	prodList.grab(spinnerImg);	
	popupPanel.grab(prodList);
	prodList.fade('in');

	var urlPath = "lib/getcontent.php?type=prodlist&cat=" + category;

	// load category list
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',		
		onSuccess: function(html) {
			// display categories
			prodList.empty();
			prodList.adopt(html);
			// enable link highlight
			var allLinks = $$('#popup_prodlist a');
			allLinks.each(function(thisLink, i) {
				thisLink.addEvent('click', function() {
					var allLinks = $$('#popup_prodlist a');
						allLinks.each(function(thisLink, i) {
						thisLink.removeClass('selected');
				       });
					this.addClass('selected');						
				} );
			});		
			// enforce action if product set
			if(selproduct>0) {
				// clear variables after the call
				selcategory = 0;
				selsubcategory =0;
				var stemp = selproduct;
				selproduct = 0;
				showProductDetails(stemp);
			}
		}
	});
	req.send();
	
	
	// ************** mark/unmark the selected link		
	
}

function showProductDetails(productid) {
	var popupPanel = $('popup_container');
	// remove previous list if exists
	if ($('popup_details')) {
		$('popup_details').destroy();
	}
	// add product details
	var prodDetails = new Element('div', {
	    'id': 'popup_details'
	});
	if ($('popup_punch')) {
		$('popup_punch').destroy();
	}
	
	prodDetails.fade('hide');
	prodDetails.grab(spinnerImg);	
	popupPanel.grab(prodDetails);
	prodDetails.fade('in');		

	var urlPath = "lib/getcontent.php?type=proddetails&page=all&prodid=" + productid + "&ie=" + ie;
	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			prodDetails.empty();
			prodDetails.adopt(html);
			applyRollovers($$("#popup_nav .rollover"));
			// handle the scrollbars
			makeScrollbar($('popup_content'), $('popup_scrollbar'), $('popup_scrollhandle'));
			// enable photo popup
			enableLargePhoto();
			// go to downloads page if required
			if(selpage!="none") {
				switchProductDetails(selproduct, selpage);
				selproduct=0;
				selcategory=0;
				selsubcategory=0;
			}
		}
	});
	req.send();  
}

function switchProductDetails(productid, page) {
	var prodColumn = $('popup_column2');	
	// mark prod as selected
	var urlPath = "lib/getcontent.php?type=proddetails&page=" + page + "&prodid=" + productid + "&ie=" + ie;
	prodColumn.empty();
	prodColumn.adopt(spinnerImg);	

	var req = new Request.HTML({
		url:urlPath, 
		method:'get',
		onSuccess: function(html) {
			prodColumn.empty();			
			prodColumn.adopt(html);
			// handle the scrollbars
			makeScrollbar($('popup_content'), $('popup_scrollbar'), $('popup_scrollhandle'));
		}
	});
	req.send();  
}

// preload assets
function PreloadImages() {
	// list images to be preloaded
	new Asset.image('images/body_bg.png');
	new Asset.image('images/container_bg.png');	
	new Asset.image('images/home_gradient_bg.png');
	new Asset.image('images/footer_bg.png');	
	// preload bars
	new Asset.image('images/prodsel_b1.png');
	new Asset.image('images/prodsel_b2.png');
	new Asset.image('images/prodsel_b3.png');
	new Asset.image('images/prodsel_b4.png');
	new Asset.image('images/prodsel_b5.png');
	new Asset.image('images/prodsel_b6.png');	
	new Asset.image('images/prodsel_b1_over.png');
	new Asset.image('images/prodsel_b2_over.png');
	new Asset.image('images/prodsel_b3_over.png');
	new Asset.image('images/prodsel_b4_over.png');
	new Asset.image('images/prodsel_b5_over.png');
	new Asset.image('images/prodsel_b6_over.png');		
	// preload product images
	new Asset.image('images/prodsel_photo1.jpg');
	new Asset.image('images/prodsel_photo2.jpg');
	new Asset.image('images/prodsel_photo3.jpg');
	new Asset.image('images/prodsel_photo4.jpg');
	new Asset.image('images/prodsel_photo5.jpg');
	new Asset.image('images/prodsel_photo6.jpg');	
}

function makeScrollbar(content,scrollbar,handle){
	if (content) {
		var contentSize = content.getSize().y;
		var scrollSize= content.getScrollSize().y;	
		var steps = scrollSize - contentSize;
	} else {
		steps = 0;
	}

	if (steps > 0) {
		var slider = new Slider(scrollbar, handle, {	
			steps: steps,
			mode: 'vertical',
			onChange: function(step){
				// Scrolls the content element in x or y direction.
				content.scrollTo(0, step);
			}
		}).set(0);
	
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 30;	
			slider.set(step);					
		});
	
		// Stops the handle dragging process when the mouse leaves the document body.
		$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
	} else {
		scrollbar.fade('hide');
	}
}	
	
function applyRollovers(rolloverButtons) {
	//if (ie==false) {
		rolloverButtons.each(function(rolloverButton, i) {
			//get path and preload images
			var butPath = rolloverButton.get('src');	
			var butLen = butPath.length;
			var butExt = butPath.substr(butLen - 4, 4);
			butPath = butPath.substr(0, butLen - 4);
			var newPath = butPath + "_over" + butExt;	
			var preload = new Asset.image(newPath);				
		
			//rollovers activate
			rolloverButton.addEvent("mouseenter", function() {
				F_addOver(this);
			});
			rolloverButton.addEvent("mouseleave", function() {						       
				F_removeOver(this);
			});	
		});
	//}
}
// functions for rollovers
function F_addOver(element) {
	var butPath = element.get('src');
	var butLen = butPath.length;
	var butExt = butPath.substr(butLen - 4, 4);
	butPath = butPath.substr(0, butLen - 4);
	var newPath = butPath + "_over" + butExt;	
	element.set('src', newPath);
}
function F_removeOver(element) {
	var butPath = element.get('src');
	var newPath = butPath.replace("_over.", ".");
	element.set('src', newPath);
}

// jump menu activator used for the country selector
function F_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}
function enableSearch() {
	$('searchgo').addEvent("click", function() {
		$('searchform').submit();
	});
	$('searchfield').addEvent("click", function() {
		$('searchfield').set("value","");
	});	
}
function subscriptionHandle() {
				var email = $("subscription_email").get("value");
				if ((email.indexOf("@")>-1) && (email.length>10)) {
					// send subscription
					var req = new Request.HTML({
						url:"lib/subscribe.php?email=" + email, 
						method:'get',
						onSuccess: function(html) {
							$('subscription_message').set("text", "Thank you, you will be notified soon!");	
							$("subscription_email").set("");
						}
					});
					req.send();  
				} else {
					$('subscription_message').set("text", "Please enter a valid email address.");
				}
}

function loadPhoto(path) {
	var popupPhoto = $('popup_photo').getElement('img');
	popupPhoto.set('src', path);
	// preload the large photo so it opens quicker
	imgSource = path.replace(".jpg", "_large.jpg");
	var myImage = new Asset.image(imgSource);
	
	// makes the popup
	$('popup_photo').removeEvents("click");	
	enableLargePhoto();
}

function enableLargePhoto() {
	$('popup_photo').addEvent("click", function() {
				// identify the img source
				var popupPhoto = $('popup_photo').getElement('img');
				var imgSource = popupPhoto.get("src");
				imgSource = imgSource.replace(".jpg", "_large.jpg");
				// display or resize the image
				var myImage = new Asset.image(imgSource, {onload: EnlargementOpen});
	});
}

function EnlargementOpen() {
	// identify source
	var popupPhoto = $('popup_photo').getElement('img');
	var imgSource = popupPhoto.get("src");
	imgSource = imgSource.replace(".jpg", "_large.jpg");
	
	// show overlay
	$('enlarg_container').tween('opacity', [0, 0.7]);

	// show image placeholder
	var enlargImgcontainer = $('enlarg_imgcontainer');
	var size = window.getSize();
	enlargImgcontainer.setStyle("left", size.x/2);
	enlargImgcontainer.fade("in");

	// enlarge image placeholder
	var finalSize = size.y-100;
	if (finalSize>700) { finalSize=700; }

	var myEffect = new Fx.Morph(enlargImgcontainer, {duration: 'normal', transition: Fx.Transitions.Sine.easeOut});
	myEffect.start({
		'height': [150, finalSize+15],
		'width': [150, finalSize],
		'left': [(size.x/2), (size.x/2 - finalSize/2)],
		'top': [20, (size.y/2 - finalSize/2)-15]
	});

	// preload image
	var myImagePreloader = new Asset.image(imgSource);

	// load image with a delay
	var showImage= function(){ 
			// load image in place
			var enlImage = $('enlarg_image');
			enlImage.set("src", imgSource);
			enlImage.setStyle("width", finalSize);
			enlImage.setStyle("height", finalSize);
			enlImage.fade("in");	
			
			// close button
			$('enlarg_close').fade("in");
			$('enlarg_close').addEvent("click", function() {
					$('enlarg_image').fade("hide");		 
					$('enlarg_imgcontainer').fade("hide");
					$('enlarg_close').fade("hide");					
					$('enlarg_image').set("src", "images/blank.gif");
					$('enlarg_image').setStyle("width", "150px");
					$('enlarg_image').setStyle("height", "150px");
					$('enlarg_imgcontainer').setStyle("width", "150px");
					$('enlarg_imgcontainer').setStyle("height", "150px");
					$('enlarg_container').fade("out");
			});

	};
	showImage.delay(1000, imgSource, finalSize); 
	
}

function enableSlr() {
	//preload large image
	//var myImagePreloader = new Asset.image('images/slr_camera.png');
	//$('slrproduct').
	
	//handle popups
	for (var i=1; i<9; i++) {
		
		$('pop'+i).fade("hide");	
		$('link'+i).i = i;
		$('link'+i).addEvent("click", function() {
					// close others
					for (var j=1; j<9; j++) {
						$('pop'+j).fade("hide");
					}
					// open popup
					var i = this.i;
					$('pop'+i).fade("in");
				
					var closeb = $('close'+i);
					closeb.i = i;
					//close button
					closeb.addEvent("mouseenter", function() {
							this.set('src', 'images/slr_close_over.png');
					}.bind(closeb))
					closeb.addEvent("mouseleave", function() {
							this.set('src', 'images/slr_close.png');
					}.bind(closeb))
					closeb.addEvent("click", function() {
							var i = this.i;
							$('pop'+i).fade("hide");
							this.removeEvents();
					}.bind(closeb))
		  });
	
	}
				
}

