// Title: 			Dufresne JavaScript File
// Author:			Devon Mitton
// Site: 			http://www.dufresne.ca
// Description:		JavaScript file with functions for site behaviour.
// Dependencies:	mootools-1.2.js
function getActivePage() {
	var querystring = String (document.location).split('/')[6];
	if (querystring) {
		return querystring.replace("-", "");
	}
	return false;
}

var GetInfo = new Class({

	code: ["i","n","f","o"],
    
	step: 0,

	initialize: function(func1,func2,func3){
		if($defined(func2))
			this.func2 = func2;
		if($defined(func3))
			this.func3 = func3;
		this.func = func1;
		document.addEvent('keyup',this.keystroke.bind(this));
	},
    
	keystroke: function(e){
		ev = new Event(e);
    	
		if(ev.key == this.code[this.step]){
			if($defined(this.func2))
				this.func2.attempt(this.step);
			this.step++;
			if(this.step == this.code.length){
				this.step = 0;
				this.func.attempt();
			}
		} else {
			this.step = 0;
			if($defined(this.func3))
				this.func3.attempt();
		}
	}
    
});

document.addEvent('domready', function() {
	
// ===== FLASH CONTENT ===== \\
	if ($('flashContent')) {

		if ($('wrapper')) {
			$('wrapper').setStyle('display', 'none');
		}

		// remove the elements with the javascript error.
		$$('.jsError').each(function(e) {
			e.destroy();
		});

		// flash content variables
		var sPath = "swf/";
		var sWidth = "545";
		var sHeight = "300";
		var sVersion = "8";
		var sBackground = "#ffffff";

		// embed flash player as per page
		if ($('index')) {
			var sFilename = "index";
		} else if ($('shop')) {
			var sHeight = "550";
			var sFilename = "store";
		} else if ($('promotions')) {
			var sHeight = "450";
			var sFilename = "store";
		} else if ($('locations')) {
			var sHeight = "400";
			var sFilename = "locations";
		} else if ($('careers')) {
			var sFilename = "careers";
		}

		// embed the flash player
		var so = new SWFObject(sPath+sFilename+".swf", sFilename, sWidth, sHeight, sVersion, sBackground);
		if (so.write("flashContent")) {
			$('flashContent').setStyles({
				height: sHeight+"px",
				border: "none"
			});
		} else {
			$('wrapper').setStyle('display', 'block');
		}
	}

// ===== SLIDING NAVIGATION ===== \\

	// remove the shop navigation cookie if you're not on the shop page
	// if ($('shop') == null) {
	// 	if (Cookie.get('dufresne_nav')) {
	// 		Cookie.remove('dufresne_nav');
	// 	}
	// }

	if ($("shop")) {		
		
		// loop through the categories
		var togglers = $$('a.toggler');
		var toggles = $$('ul.toggle');
		
		var activePage = getActivePage();
		
		if (activePage) {}
		var active = false;
		
		// remove the href attribute and make the sublists display as block
		togglers.each(function(e, i) {
			e.removeAttribute("href");
			e.getNext().setStyle('display', 'block');
			if (e.get("id") == activePage+"Toggle") {
				active = i;
			}
		});
		
		var catalogueNav = new Accordion(togglers, '.toggle', {
			display: false,
			opacity: false,
			alwaysHide: true,
			duration: 200,
			transition: Fx.Transitions.Expo.easeOut,
			show: active
		}, $('shopNavigation'));

	}

// ===== TAB SHELF ===== \\
	if ($('tabShelf')) {
		// instantiate the variables
		var tabShelf = $('tabShelf');
		var tabBox = $('tabBox');

		tabShelf.style.overflow = "hidden";
		tabShelf.style.height = "25px";

		// set up the final width for the tab box
		var tabWidth = document.getElementById('tabWidth').clientWidth+5;
		tabBox.style.width = tabWidth+"px";
		tabBox.style.position = "absolute";

		//adjust this equation to allow for paged sliding....

		if (tabWidth > tabShelf.clientWidth) {

			var tabSlider = new Fx.Styles('tabBox', {duration: 1000, transition: Fx.Transitions.Expo.easeOut});
			var tabShelfWidth = tabShelf.clientWidth;

			// create the right button
			rightButton = document.createElement("p");
			rightButton.setAttribute("id", "rightButton");
			rightButton.setAttribute("onclick", "testRight()");
			tabShelf.appendChild(rightButton);
			rightButton.innerHTML = "Next &raquo;"

			// create the left button
			leftButton = document.createElement("p");
			leftButton.setAttribute("id", "leftButton");
			leftButton.setAttribute("onclick", "testLeft()");
			tabShelf.appendChild(leftButton);
			leftButton.innerHTML = "&laquo Back";


			leftButton.style.display = "none";

			leftButton.onclick = function() {
				if (tabBox.offsetLeft < 0) {
					if (tabBox.offsetLeft+tabShelfWidth > 0) {
						tabSlider.start({
							'left': 0
						});
						leftButton.style.display = "none";
					} else {
						tabSlider.start({
							'left': tabBox.offsetLeft + tabShelfWidth
						});
					}
					if (rightButton.style.display == "none") {
						rightButton.style.display = "block";
					}

				}
			};

			rightButton.onclick = function() {
				if (tabBox.offsetLeft > (0-tabWidth)) {
					if (tabBox.offsetLeft-(tabShelfWidth*2) < 0-tabWidth) {
						tabSlider.start({
							'left': 0-tabWidth+tabShelfWidth
						});
						rightButton.style.display = "none";
					} else {
						tabSlider.start({
							'left': tabBox.offsetLeft - tabShelfWidth
						});
					}
					if (leftButton.style.display == "none") {
						leftButton.style.display = "block";
					}

				}
			};
		}
	}
	
// ===== FAQ ACCORDIAN ===== \\
	if ($('answers')) {
		var accordion = new Accordion('p.q', 'div.a', {
			display: false,
			alwaysHide: true,
			duration: 200,
			transition: Fx.Transitions.Expo.easeOut
		}, $('answers'));
	}
	
// ===== LOCATION STUFF ===== \\

	if ($('location-box')) {
		
		var cookie = Cookie.write('dufresne_loc_s', 'true', {duration: 30, path:"/"});
		
		var hide_btn = $('location-box-hide-btn');
		hide_btn.addEvent("click", function(evt) {
			evt.stop();
			
			var location_box = $('location-box');
			
			var close_location_box = new Fx.Slide(location_box,{duration: '300',onComplete:function(e){location_box.destroy();}}).slideOut();
			
		});
		
	}
	
	if ($('postal-code-box')) {
		
		var postal_code_box = $('postal-code-box').setStyle("display", "block");
		var postal_code_slider = new Fx.Slide(postal_code_box, {duration: '300', transition: Fx.Transitions.Expo.easeOut}).hide();
		
		var hide_btn = $('postal-code-box-hide-btn');
		hide_btn.addEvent("click", function(evt){
			
			evt.stop();
			postal_code_slider.slideOut();
			
		});
		
		var show_btns = $$('.postal-code-show-btn');
		show_btns.each(function(show_btn){
			
			show_btn.addEvent("click", function(evt){
				
				evt.stop();
				postal_code_slider.slideIn();
				
			});
			
		});
		
		var postal_code_form = $('postal-code-form');
		postal_code_form.addEvent('submit', function(evt){
			
			evt.stop();
			var pc1 = $('postalcode1');
			var pc2 = $('postalcode2');
			
			var postal_code = pc1.get("value") + " " + pc2.get('value');
			
			// validations
			
			// empty
			if (pc1.value == "" || pc2.value == "") {
				alert("Postal Code fields can't be empty.");
				return;
			}
			
			// length
			if (pc1.value.length < 3 || pc2.value.lenght < 3) {
				alert("Postal Code fields each must contain 3 characters.");
				return;
			}
			
			// format
			var pcRegEx = /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/;
			var postalCode = pc1.value.toUpperCase()+' '+pc2.value.toUpperCase();
			
			if (!postalCode.test(pcRegEx, 'i')) {
				alert("Not a valid Postal Code: A1B 2C3");
				return;
			}
			
			// submit the form.
			var submitForm = new Request({
				url: postal_code_form.get("action"),
				method: postal_code_form.get("method"),
				onSuccess: function(response) {
					
					// alert(response);
					
					postal_code_slider.slideOut();
					
					if (Cookie.read('dufresne_loc', {path:"/"}) != null) {
						Cookie.dispose('dufresne_loc', {path:"/"});
					}
					
					// use the information retrieved from the response.
					Cookie.write('dufresne_loc', response, {duration: 30, path: "/"});
					
					location.reload();
					
				},
				onFailure: function(xhr) {
					alert('There was a problem submitting the form. Please try again.');
				}
			}).send("postal_code="+postalCode);
			
		});
		
	}
	
	if ($("shop")) {
		
		if ($("itemDetails")) {
			
			var requested = false;
			var returned = false;

			getinfo = new GetInfo(function() {


				var get_info_data = $("product_id");
				var data = get_info_data.get("data");

				if (data != null && requested == false) {

					requested = true;
					returned = true;
					var request = new Request.JSON({
						url: "/info",
						method: "get",

						onSuccess: function(responseJson, responseText) {
							
							var vendor_name = "<p><strong>Vendor Name:</strong> " + (responseJson.vendorName || "") + "</p>";
							var vendor_number = "<p><strong>Vendor Number:</strong> " + (responseJson.vendorNumber || "") + "</p>";
							
							var more_info = new Element("div", {
								"class" : "notice",
								"html" : vendor_name + vendor_number
							}).injectInside("itemInfo");

							more_info.highlight();

						},

						onFailure: function(xhr) {


						}

					}).send("product=" + data);
				}			

			});
			
		}
		
		if ($("boxList")) {
		
			var requested = false;
			var returned = false;
			
			getInfo = new GetInfo(function() {
				
				var items = $$(".get-info");
				var total = items.length;
				// var count = 0;

				items.each(function(item, index) {
					
					var data = item.get("data");
					
					if (data != null && requested == false) {
						
						returned = true;
						
						var request = new Request.JSON({
							url: "/info",
							method: "get",
							
							onSuccess: function(responseJson, responseText) {
								
								var new_title = (responseJson.vendorName || "") + " | " + (responseJson.vendorNumber || "");
								item.getElement("img").set("alt", new_title).set("title", new_title);
								
							},
							
							onFailure: function(xhr) {
								
							}
							
						}).send("product=" + data);
						
					}
					
					if ((index + 1) == total) {
						
						if (returned && !requested) {
							requested = true;
							show_notice();
						}
						
					}
					
				});
				
			});
			
			
		}
		
	}
	
	function show_notice() {
		
		var headline = $("content").getElement("h1");
		headline.set("text", headline.get("text") + " | More Info");
		
		var notice = new Element("p", {
			"class" : "notice",
			"text" : "Hover over an image to get additional information.",
			"styles" : {
				"opacity" : 0
			}
		}).injectAfter(headline).fade("in");
		
	}


/*	
// ===== SEARCH DROPDOWN ===== \\
	if (search = document.getElementById('searchToggle')) {

		var header = document.getElementById('header');

		// create the form
		var miniSearchForm = document.createElement('form');
		miniSearchForm.setAttribute("id", "miniSearch")
		miniSearchForm.setAttribute("action", "search");
		miniSearchForm.setAttribute("method", "post");

		// create the label
		var searchLabel = document.createElement('label');
		searchLabel.setAttribute("for", "searchField");

		// create the label text
		var searchLabelText = document.createTextNode("Search:");

		// create the input field
		var searchFieldString = "Search For Products";
		var searchField = document.createElement('input');
		searchField.setAttribute("id", "searchField");
		searchField.setAttribute("type", "text");
		searchField.setAttribute("name", "search");
		searchField.setAttribute("value", searchFieldString);

		// create the submit button
		var searchSubmit = document.createElement('input');
		searchSubmit.setAttribute("id", "submitSearch");
		searchSubmit.setAttribute("type", "submit");
		searchSubmit.setAttribute("name", "submit");
		searchSubmit.setAttribute("value", "Go!");

		// apply the form
		header.appendChild(miniSearchForm);
			miniSearchForm.appendChild(searchField);
			miniSearchForm.appendChild(searchSubmit);

		// the click action
		miniSearchForm.style.opacity = 0;
		miniSearchForm.style.visibility = "hidden";
		$('searchToggle').addEvent('click', function(e){
			e = new Event(e);
			if (miniSearchForm.style.opacity == 0) {
				var fx = $(miniSearchForm).effect('opacity').start(1);
			} else {
				var fx = $(miniSearchForm).effect('opacity').start(0);
			}
			e.stop();
		});

		// focus
		searchField.onfocus = function() {
			if (searchField.value == searchFieldString) {
				searchField.value = "";
			}
		}
		// blur
		searchField.onblur = function() {
			if (searchField.value == "") {
				searchField.value = searchFieldString;
			}
		}	
	}*/


// ===== VALIDATIONS ===== \\
	// if ($("validate")) {
	// 	var formList = $$('#validate li');
	// 	
	// 	formList.each(function(e) {
	// 		e.addEvent('mouseenter', function(){
	// 			e.setStyle("background", "#eee");
	// 		});
	// 		e.addEvent('mouseleave', function(){
	// 			e.setStyle("background", "none");
	// 		});
	// 	});
	// }
	
});

// =====  SEND STUDIO FUNCTIONS ===== \\

function CheckMultiple(name) 
{
	theFrm = document.frmSS;
	for (var i=0; i < theFrm.length; i++) 
	{
		fldObj = theFrm.elements[i];
		var fieldnamecheck=fldObj.name.indexOf(name);
		if (fieldnamecheck != -1) {
			if (fldObj.checked) {
				return true;
			}
		}
	}
	return false;
}

if ($("subscribe")) {
// check multi checkboxes based on the name passed in.
	function CheckSS() {
		theFrm = document.frmSS;
		hasDot = theFrm.Email.value.indexOf(".");
		hasAt = theFrm.Email.value.indexOf("@");
		
		if (hasDot == -1 || hasAt == -1) {
			alert("Please enter a valid email address.");
			theFrm.Email.focus();
			theFrm.Email.select();
			return false;
		}
		valcheck = document.getElementById("Fields[3]");
		if (valcheck.value == "") {
			alert("Please enter a value for the 'First Name:' field.");
			valcheck.focus();
			valcheck.select();
			return false;
		} else {
			var minsize_3 = 0;
			var maxsize_3 = 100;
			var fieldlength = 0;
			fieldlength = valcheck.value.length;
			if (fieldlength < minsize_3) {
				alert("You must enter a value for the 'First Name:' field longer than " + minsize_3 + " characters");
				valcheck.focus();
				return false;
			}
			if (fieldlength > maxsize_3) {
				alert("You must enter a value for the 'First Name:' field no longer than " + maxsize_3 + " characters");
				valcheck.focus();
				return false;
			}
		}

		valcheck = document.getElementById("Fields[4]");
		if (valcheck.value == "") {
			alert("Please enter a value for the 'Last Name' field.");
			valcheck.focus();
			valcheck.select();
			return false;
		} else {
			var minsize_4 = 0;
			var maxsize_4 = 100;
			var fieldlength = 0;
			fieldlength = valcheck.value.length;
			if (fieldlength < minsize_4) {
				alert("You must enter a value for the 'Last Name' field longer than " + minsize_4 + " characters");
				valcheck.focus();
				return false;
			}
			if (fieldlength > maxsize_4) {
				alert("You must enter a value for the 'Last Name' field no longer than " + maxsize_4 + " characters");
				valcheck.focus();
				return false;
			}
		}
		return true;
	}
} else if ($("unsubscribe")) {
	function CheckSS() {
		theFrm = document.frmSS;
		hasDot = theFrm.Email.value.indexOf(".");
		hasAt = theFrm.Email.value.indexOf("@");
		if (hasDot == -1 || hasAt == -1) {
			alert("Please enter a valid email address.");
			theFrm.Email.focus();
			theFrm.Email.select();
			return false;
		}
		return true;
	}
}