var current_part_number = '';

function slideDrawer() {
	var drawer = $('drawer');
	var flood = $('drawerFlood');
	var arrayPageSize = getPageSize();
	flood.style.height = arrayPageSize[1] + 'px';
	flood.style.width = '100%';
	if (!drawer.hasClassName('slid')) {
		new Effect.Opacity(flood, {duration:.2, from:0.0, to:0.7, afterFinish: function() {
			new Effect.Move(drawer, {x:-27, y:-6, duration:.4, mode:'absolute'});			
		}})
		drawer.addClassName('slid');
	}
	else if (drawer.hasClassName('slid')) {
		if (current_part_number) {
			new Effect.Opacity($('ciSlide'), {from:.99, to:0.0, duration:.2});			
		}
		new Effect.Move(drawer, {x:-27, y:-600, duration:.4, delay:.2, mode:'absolute', afterFinish: function() {
			new Effect.Opacity(flood, {duration:.2, from:0.7, to:0.0, afterFinish: function() {
				flood.style.height = '0px';
				flood.style.width = '0px';
			}});
		}});
		current_part_number = '';
		drawer.removeClassName('slid');		
	}
}

function slideDrawerZip(part_number) {
	if (part_number == null) {
		new Effect.Opacity($('ciSlide'), {from:0.99, to:0.0, duration:.4});			
		current_part_number = '';
	}
	else if (current_part_number != part_number) {
		if (current_part_number == '') {
			var zipFormHtml = 'Enter your zip code to search nearby retailers for <b>'+ part_number +':</b>'+cii_ppp_api(0,part_number,'',-1,1815,-1,-1,-1,-1,'US','','');
			$('zipForm').innerHTML = zipFormHtml;				
			new Effect.Opacity($('ciSlide'), {from:0.0, to:0.99, duration:.4});	
		}
		else {
			new Effect.Opacity($('ciSlide'), {from:0.99, to:0.0, duration:.4, afterFinish: function() {
				var zipFormHtml = 'Enter your zip code to search nearby retailers for <b>'+ part_number +':</b>'+cii_ppp_api(0,part_number,'',-1,1815,-1,-1,-1,-1,'US','','');
				$('zipForm').innerHTML = zipFormHtml;				
				new Effect.Opacity($('ciSlide'), {from:0.0, to:0.99, duration:.4});	
			}})			
		}
		current_part_number = part_number;
	}
}






function openPressImage(div) {
	if (!$(div).hasClassName('opened')) {
		new Effect.BlindDown($(div), {duration:.3});
		$(div).addClassName('opened');
	}
}



function switchImg(filename) {
	var stageImg = $('stageImg');
	stageImg.src = filename;
}

function blindUpDiv(div) {
	new Effect.BlindUp(div, {duration:.2});
}

// // array of clouds
// // each cloud tracks chosen prodbox divs
// var clouds = new Array();
// 
// function cloudChoose(divName, name, bundleSize) {
// 	
// 	if (!clouds[name]) {
// 		clouds[name] = new Array();
// 	}
// 
// 	cloud = clouds[name];
// 
// 	if (cloud.length >= size) {
// 		killDiv = cloud.shift();
// 		hotToggle(killDiv, 'HIDE');
// 	}
// 
// 	var chooserDiv = "choose" + divName;
// 	cloud.push(chooserDiv);
// 	hotToggle(chooserDiv, 'HIDE');
// 	slideSku(divName);
// 	
// }

// 'choose' action for cloud sku
// currently only handles 1 sku per cloud


/* BUNDLE / SKU DIV LOGIC *******************************************************/

var chosenSkus = new Array(); 				// contains active sku choices; stored as cloudName => partNumber
var bundle_skus_array = new Array();		// contains skus to be passed to addSkusToCart

function chooseSkuForBundle(cloudName, partNumber, totalBundleSize) {
	// slide out buttons
	slideSku(cloudName+partNumber);
	
	// add/replace chosen sku in current cloud
	oldPartNumber = chosenSkus[cloudName];
	if (oldPartNumber) {
		$("choose"+cloudName+oldPartNumber).addClassName('HIDE');
		removeFromBundleArray(oldPartNumber);
	}
	
	$("choose"+cloudName+partNumber).removeClassName('HIDE');
	chosenSkus[cloudName] = partNumber;
		
	addToBundleArray(partNumber);
	checkIfCloudIsComplete(cloudName);
	checkIfBundleIsComplete(totalBundleSize);	
}

function addToBundleArray(sku){
	bundle_skus_array.push(sku);
}

function removeFromBundleArray(sku){
	var index; 
	for ( index in bundle_skus_array)
	{
		if (sku == bundle_skus_array[index]){
			bundle_skus_array.splice(index, 1);
			break;
		}
	}
}

function checkIfCloudIsComplete(cloudName) {
	doneText = $('bundleReady'+cloudName.substring(5,6));
	if (chosenSkus[cloudName]) {
		doneText.removeClassName('HIDE');
	}
	else {
		doneText.addClassName('HIDE');
	}
}

function checkIfBundleIsComplete(bundleSize) {
	if(bundle_skus_array.length == bundleSize) {
		$('bundleAddLink').removeClassName('disabled');
		$('bundleDone').removeClassName('HIDE');
		return true;
	}
	else {
		$('bundleAddLink').addClassName('disabled');
		$('bundleDone').addClassName('HIDE');
		return false;
	}
}

function slideSku(divId) {
	var invisiblediv = $("i"+divId);
	var sliderdiv = $("slide"+divId);
	var choosediv = $("choose"+divId);

	if (sliderdiv.hasClassName('slid')) {
		new Effect.Move(sliderdiv, {y:30, duration:.2});
		sliderdiv.removeClassName('slid');
		invisiblediv.style.zIndex = 103;
	}
	else if (!sliderdiv.hasClassName('slid')) {
		// if in a bundle cloud
		if (choosediv && (!choosediv.hasClassName('HIDE'))) {
			choosediv.addClassName('HIDE');
			//extract part number ...
			var partnumber = divId.substring(6);
			removeFromBundleArray(partnumber);
			//extract cloud id ...
			var cloudName = divId.substring(0, 7);
			$('bundleAddLink').addClassName('disabled');
			$('bundleDone').addClassName('HIDE');
		}
		// standard: slide out buttons
		else {
			new Effect.Move(sliderdiv, {y:-30, duration:.2});
			sliderdiv.addClassName('slid');		
			invisiblediv.style.zIndex = 98;
		}
	}
}

// Given an array of skus, create and submit a form that
// adds them to the cart
function addSkusToCart(skus, bundleSize) {
	if (checkIfBundleIsComplete(bundleSize)) {
	  var f = document.createElement('form'); 
	  f.style.display = 'none'; 
	  document.body.appendChild(f); 
	  f.method = 'POST'; 
	  f.action = '/cart/add_skus'
	  skus.each(function(sku) {
	    input = document.createElement('input')
	    input.name = 'sku_ids[]'
	    input.value = sku
	    f.appendChild(input)
	  })
	  f.submit();
	  return false;		
	}
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


function hotToggle(div, cssClass) {
	if (typeof div == 'string') {
		div = document.getElementById(div);
	}
	if (jscss('check', div, cssClass)) {
		jscss('remove', div, cssClass);
	}
	else {
		jscss('add', div, cssClass);
	}
}

function hotAddClass(div, cssClass) {
	if (typeof div == 'string') {
		div = document.getElementById(div);
	}
	if (!jscss('check', div, cssClass)) {
		jscss('add', div, cssClass);
	}
}

function hotRemoveClass(div, cssClass) {
	if (typeof div == 'string') {
		div = document.getElementById(div);
	}
	if (jscss('check', div, cssClass)) {
		jscss('remove', div, cssClass);
	}
}



/* from http://onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html */

function jscss(a,o,c1,c2)
{
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): 
      o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}


/* JAVASCRIPT IMAGE ROLLOVERS / VIA HESIDO */


// //If the browser is W3 DOM compliant, execute setImageSwaps function
// if (document.getElementsByTagName && document.getElementById) {
// if (window.addEventListener) window.addEventListener('load', setImageSwaps, false);
// else if (window.attachEvent) window.attachEvent('onload', setImageSwaps);
// }
// 
// //When document loads, apply the prepareImageSwap function to various images with our desired settings
// function setImageSwaps() {
// //Hover with restore, most basic usage - for any image in document.body that are not yet processed (function accepts elements,too)
// prepareImageSwap(document.body);
// //Note that once an image is processed, it won't be processed again, so you should set more specific images first, e.g. document.body, as it is the grand container, has to be processed last.
// }
// 
// 
// function prepareImageSwap(elem,mouseOver,mouseOutRestore,mouseDown,mouseUpRestore,mouseOut,mouseUp) { 
//     if (typeof(elem) == 'string') elem = document.getElementById(elem); 
//     if (elem == null) return; 
//     var regg = /(.*)(_off\.)([^\.]{3,})$/ 
//     var prel = new Array(), img, imgList, imgsrc, mtchd; 
//     imgList = elem.getElementsByTagName('img'); 
//     for (var i=0; img = imgList[i]; i++) { 
//         if (!img.rolloverSet && img.src.match(regg)) { 
//             mtchd = img.src.match(regg); 
//             img.hoverSRC = mtchd[1]+'_on.'+ mtchd[3]; 
//             img.outSRC = img.src; 
//             if (typeof(mouseOver) != 'undefined') { 
//                 img.hoverSRC = (mouseOver) ? mtchd[1]+'_on.'+ mtchd[3] : false; 
//                 img.outSRC = (mouseOut) ? mtchd[1]+'_ou.'+ mtchd[3] : (mouseOver && mouseOutRestore) ? img.src : false; 
//                 img.mdownSRC = (mouseDown) ? mtchd[1]+'_md.' + mtchd[3] : false; 
//                 img.mupSRC = (mouseUp) ? mtchd[1]+'_mu.' + mtchd[3] : (mouseOver && mouseDown && mouseUpRestore) ? img.hoverSRC : (mouseDown && mouseUpRestore) ? img.src : false; 
//                 } 
//             if (img.hoverSRC) {preLoadImg(img.hoverSRC); img.onmouseover = imgHoverSwap;} 
//             if (img.outSRC) {preLoadImg(img.outSRC); img.onmouseout = imgOutSwap;} 
//             if (img.mdownSRC) {preLoadImg(img.mdownSRC); img.onmousedown = imgMouseDownSwap;} 
//             if (img.mupSRC) {preLoadImg(img.mupSRC); img.onmouseup = imgMouseUpSwap;} 
//             img.rolloverSet = true; 
//         } 
//     } 
//     function preLoadImg(imgSrc) { 
//         prel[prel.length] = new Image(); prel[prel.length-1].src = imgSrc; 
//     } 
// } 
// function imgHoverSwap() {this.src = this.hoverSRC;} 
// function imgOutSwap() {this.src = this.outSRC;} 
// function imgMouseDownSwap() {this.src = this.mdownSRC;} 
// function imgMouseUpSwap() {this.src = this.mupSRC;}
// 
function checkForm(form) {
	email = form.elements['contact[email]'].value;
	if (!validEmail(email)) {
		alert('Please enter a valid email address');
		return false
	}
	else {
		for (var i in form.elements) {
			if (form.elements[i].value == '') {
				alert('All blanks are required - make sure to fill out the whole form.');
				return false
			}
		}
	}
	return true
}

function checkEmail(email) {
	if (!validEmail(email)) {
		alert('Please enter a valid email address');
		return false
	}
	return true
}

function validEmail(email) {
  return email.match(/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i)
}





// /* SLIDE OUT NEWS ITEMS ON HOMEPAGE */
// 
// var tickerOpen = false;
// 
// function tickerExpand() {
// 	var goTicker = new Fx.Style($('tickerList'), 'height', {duration:400});
// 	if (!tickerOpen) {
// 		goTicker.start(158);
// 		tickerOpen = true;
// 	}
// 	else {
// 		goTicker.start(30);
// 		tickerOpen = false;
// 	}
// }
// 
//