if(typeof console == "undefined"){
	console = {};
	console.log = function(){};
}else{
	if(Browser.Engine.trident && Browser.Engine.version > 7)
	console.clear()
}
// history
var H = {};
function supaNavigation(){
	var nav = $$('.nav');
	var sub = $$('.subNav');
	var clearNav = function(){
		nav.each(function(el){
			el.removeClass('active')
		})
	}	
	var clearSub = function(){
		sub.each(function(el){
			el.setStyle('display','none');
		})
	}	
	nav.each(function(el,index){
		el.addEvents({
			'mouseenter':function(){
				clearNav();
				clearSub();
				el.addClass('active')
				sub[index].setStyle('display','block');
			}
		})
	})
	sub.each(function(el,index){
		el.addEvents({
			'mouseleave':function(){
				sub[index].setStyle('display','none')
				clearNav();
			}
		})
	})
}
window.addEvent('domready',supaNavigation)
var toutlist = 	{"touts":[
	{"toutClass":"halulite","link":"/technology/detail/nform_ultralight/"},
	{"toutClass":"technology","link":"/technology/detail/pinnacle/"},
	{"toutClass":"blog","link":"/blog"}
]}

/* *** load touts *** */
function loadTouts(touts, target) {
	var addTout = function(el, index) {
		el.inject(target);
		var fx = new Fx.Morph(el,{transition: Fx.Transitions.Quad.easeIn,duration:350})
		fx.start({'opacity':1});
	};
	
	var chainLoad = new Chain();
	
	touts.each(function(tout, index) {
	chainLoad.chain(addTout.pass([tout, index]))
	});
	var runChain = function() {
	chainLoad.callChain();
	};
	var timer = runChain.periodical(200);
};
/* *** create touts *** */
function createTouts(){
	if( ! $type($('toutSet'))){return false;}
	var target = $('toutSet');

	var touts = [];
	toutlist.touts.each(function(el, index, group){
		var tout = new Element('a',{
		'class':el.toutClass + ' tout',
		'href':el.link,
		'styles':({
			'opacity':0
			})
		});
		touts.push(tout)
	})
	loadTouts(touts, target)
};
window.addEvent('domready',createTouts); 	
	
/* *** cat accordion *** */
//var acc = {};
function initCatAcc(){
	if( ! $type($('alphaNavigation')) || $('nonAccordion')){return false;}
	//if( ! displaypos) {var d = 0}
	acc = new Fx.Accordion($$('.accToggle'),$$('.accTarget'),{
		duration:200,
		transition: Fx.Transitions.Quad.easeIn,
		display: ACCDISPLAY,
    	alwaysHide: false,
    	onActive:function(toggler, element){
    		toggler.addClass('actv');
    	},
    	onBackground:function(toggler, element){
    		toggler.removeClass('actv');
    	}
	})
	var close = $$('.noAcc')
//	close.each(function(el){
//		el.addEvent('click',function(e){
//			e.stop();
//			acc.display(-1);
//		})
//	})

}
 
window.addEvent('domready',initCatAcc); 

function	setPwBreadcrumb(url){
	url = url._currentLocation;
	var t = url.split('/')[1];
	var m = t.replace(/_/g," ");

	$$('.foo').each(function(el){
		el.dispose()
	})
	
	
	$('sukka').set('text', m)
}
function fireSelection(value){
	var url = '';
	//get history location or current url
	url = window.top.location.pathname.split('/products/')[1];
	console.log(window.top.location);
	
	var removePagination = /P(.[0-9]{1,6})/;
	url = url.split(removePagination)[0];
	
	// get rid of previous sort filters
	var removeFilter = /\/price\/|\/weight\/|\/new\//g;
	var val = '';
	if(url.match(removeFilter)){
		val = '/' + value
	}else{
		val = value;
	}
	url = url.split(removeFilter)[0];
	
	url = url + val;

	//debugger;	
	
	// add back in products segment, and append filter value;
	url = '/products/' + url;
	// update the breadcrumb with the last change
	window.location = url;
}


function fireActivitySelection(value){
	var url = '';
	//get history location or current url
	url = window.top.location.pathname.split('/activities/')[1];
	
	var removePagination = /P(.[0-9]{1,6})/;
	url = url.split(removePagination)[0];
	
	// get rid of previous sort filters
	var removeFilter = /\/price\/|\/weight\/|\/new\//g;
	var val = '';
	if(url.match(removeFilter)){
		val = '/' + value
	}else{
		val = value;
	}
	url = url.split(removeFilter)[0];
	
	url = url + val;

	//debugger;	
	
	// add back in products segment, and append filter value;
	url = '/activities/' + url;
	// update the breadcrumb with the last change
	window.location = url;
}


/* ajax version
function fireSelection(value){
	var url = '';
	//get history location or current url
	if(H.hist._currentLocation){
		url = H.hist._currentLocation ;
	}else{
		url = window.top.location.pathname.split('/products/')[1];
	}
	url = url.split('/#')[0];
	
	//get rid of pagination
	var removePagination = /P(.[0-9]{1,6})/;
	url = url.split(removePagination)[0];
	
	// get rid of previous sort filters
	var removeFilter = /\/price\/|\/weight\/|\/new\//g;
	var val = '';
	if(url.match(removeFilter)){
		val = '/' + value
	}else{
		val = value;
	}
	url = url.split(removeFilter)[0];
	
	url = url + val;

	//debugger;	
	
	// add back in products segment, and append filter value;
	url = '/products/' + url;
	// update the breadcrumb with the last change
	window.location = url;
}
*/

function fireTabSelection(e,trigger,target,index){
	var allContent = [];
	var setContent = [];
	allContent.combine([trigger,target])
	setContent.combine([trigger[index],target[index]])
	allContent.each(function(el){
		el.removeClass('active')
	})
	setContent.each(function(el){
		el.addClass('active')
	})
}
function initSubTabs(){
	if($$('.sub_tabs').length == 0){return false;}
	var trigger = $('sub_tabs').getElements('li');
	var target = $('sub_tab_content').getElements('.sc');
	// display first tab & content //
	trigger[0].addClass('active');
	target[0].addClass('active');
	trigger.each(function(el, index){
		el.addEvent('click', fireTabSelection.bindWithEvent(this,[trigger,target,index]))
	})
}
window.addEvent('domready',initSubTabs);

function setPdpImage(i, source){
	
	//source = source.primary
	source = source[i]
	source = source.replace('.jpg','')
	target = $('sub_main_content');
	target.empty();
	url = '/resources/images/product_images/' + source;
	
	//dev:   
	//stage: /request/pdp_sized_images/63451_h1_g
	
	
	
	var req = new Request({
		url:'/request/pdp_sized_images/' + source,
		onSuccess : function(responseText, responseXml) {
			var initialImage = new Asset.image(responseText, {
				'styles':({
					'opacity':0
				})
			})
			initialImage.inject(target).fade('in');
		}
	}).send();
}
function swapPdpImage(i, source){
	setPdpImage(i, source);
	$('zoom_image').set('href','/resources/images/product_images/'+source[i])
}
/*
function swapPdpSwatch(i, secondary){
	setPdpImage(i, secondary)
	$('zoom_image').set('href','/resources/images/product_images/'+secondary[i])
}
*/
function initProductView(){
	if(typeof(product_info) == 'undefined'){return false;}
	
	/* this might be redundant	
	if(product_info.length == 1){
		$$('.tmp').each(function(el){el.setStyle('display','none')});
	}
	*/
	
	var primary    = [];
	var secondary  = [];
	
	
	//create new arrays for primary & secondary
	//primary
	
	product_info.each(function(item, index){
		if(item.primary){
			primary.combine([item.primary])
		}else if(item.secondary){
			secondary.combine([item.secondary])
		}
	})
	
	var primary_len = primary.length;
	var secondary_len = secondary.length - primary_len;
	
	// if a single image is returned, nuke the contols, and display the initial color swatch instead
	if(primary_len == 1){
		$$('.tmp').each(function(el){el.setStyle('display','none')});
		$('currColor').setStyle('display','block');
	}
	
	// set first image
	swapPdpImage(0, primary);

	// set up controls
	var zoom = $('zoom_image');
	var display = product_info[0].primary;
	zoom.set('href','/resources/images/product_images/' + display)
	
	//zoom event
	zoom.addEvent('click',function(e){
		e.stop();
		var overlay = new Overlay(this.href,{ 
	    	containerId:'overlayContainer',
	    	dimmerId:'dimmer',
	    	close:true
	   	})
	})

	
	/*
	// handled in pdpimage class now, create swatch for curent color, only used if no additional images
	var curSwatch = $('curSwatch');
	curSwatch.addEvent('click', setPdpImage.pass([0, primary]));
	*/
	
	var pdp = new pdpimage({
		_target:$('sub_main_content'),
		_primaryArray: primary,
		_secondaryArray: secondary,
		_len:product_info.length,
		_primaryLen:primary_len,
		_secondaryLen:secondary_len,
		_next:$('next_image'),
		_previous:$('previous_image'),
		_swatches:$$('.swatch'),
		_currentColor: $('currSwatch'),
		onTorpedo:swapPdpImage
	})
	
}
window.addEvent('domready',initProductView);

function initBuyOnline(){
	if( ! $type($('buy-online'))){return false;}
	var trigger = $('buy-online')
	trigger.addEvent('click',function(e){
		e.stop();
		var overlay = new Overlay(this.href,{ 
	    	containerId:'buyNowOverlay',
	    	dimmerId:'dimmer',
			type:'html',
	    	close:true
	   	})
	})
}
window.addEvent('domready',initBuyOnline);


/* *** Home Marquee *** */
var marqueelist = 	{"items":[
	{"link":"/products/pdp/halulite_microdualist/","id":"halLink"},
	{"link":"/products/pdp/.75_l_infinity_dukjug-_red/","id":"infinityLink"},
	{"link":"/products/pdp/pinnacle_camper/","id":"pinnLink"}
]}
function swapMarquee(index){
	var target = $('marquee').getElements('.marqueeImage');
	target.each(function(el){
		el.fade('out');
	})
	target[index].fade('in');
	var trigger = $$('#control a');
	var mLink = target.getElement('a');
	trigger.each(function(el){
		el.removeClass('active');
	})
	mLink.set({
		'id': marqueelist.items[index].id,
		'href': marqueelist.items[index].link
	})
	trigger[index].addClass('active');
}
function initMarquee(){
	if( ! $type($('marquee'))){return false;}
	var trigger = $$('#control a');
	trigger.each(function(el,index){
		el.addEvent('click',swapMarquee.pass(index))
	})
	swapMarquee(0);
	var rotate = new Rotation({
		 _itemClass:'.item',
		 _time:7500,
		 _len:3,
		 onTorpedo:swapMarquee
 	})
}
 
window.addEvent('domready',initMarquee);

/* product wall and history */
function buildwall(responseTree, responseElements, responseHTML, responseJavaScript){
		$('pwall').empty();
		$('pwall').set('html',responseHTML);
		$exec(responseJavaScript);
	}
function initHistorySettings(h, flag){
	setPwBreadcrumb(h);
	var newReq = '/request/' + h._currentLocation;
	var randomnumber = Math.floor(Math.random()*9999999);
	new Request.HTML({
		url:newReq.replace('#','') + '?n=' + randomnumber,
		noCache:true,
		evalScripts:false,
		evalResponse:false,
		onSuccess:buildwall.bind(this) // should go though history manger now
	}).send();	
	
}
function initWall(){
	if( ! $type($('catNav'))){return false;}
	if( ! $type(H.hist)){
		H.hist = new HistoryManager();
	}
	//console.log('curr h: ',H.hist)

	if(H.hist._currentLocation){
		initHistorySettings(H.hist);
	}
	H.hist.addEvent('onHistoryChange', initHistorySettings.pass([H.hist,true]));
	var trigger = $$('#catNav a');
	trigger.each(function(el){
		new Productwall(el,{target:'pwall',history:H.hist})
		//el.addEvent('click', historyController.bindWithEvent(this,[H.hist]));
	})
}

//window.addEvent('domready',initWall);

function activitiesPagination() {
	var pBar = $('activitiesPagination');
	if (pBar) {
		
		pBar.replaces($('topBar'));
	}	
}
window.addEvent('domready', activitiesPagination);

function launchTechOverlay(e){
	e.stop()
	var overlay = new Overlay(null,{
            type:'clone',
            containerId:'techFlash',
            dimmerId:'dimmer',              
            close:true                     
       });
}

function initTechPdp(){
	if( ! $type($('techPdpOverlay'))){return false;}
	$('techPdpOverlay').addEvent('click', launchTechOverlay.bindWithEvent(this));
	
	var target = $('techFlashReplace');
	var wwSwf = new Swiff('/resources/swf/tech/'+ myTech +'/gsi.swf', {
		id: 'tech',
	    width: 400,
		height: 650,
		params: {
			wmode: 'transparent',
			allowScriptAccess: 'always',
			scale: 'noscale'
		},
		vars: {
			configPath: '/resources/swf/tech/'+ myTech +'/resources/xml/config.xml'
		}
	});
	target.empty();
	target.adopt(wwSwf);
	
}
window.addEvent('domready', initTechPdp);
