/*
* UTILITIES
*/
if(typeof console != "object"){console={log:function(){}}}// log failsafe
// Array.prototype.remove = function(from, to) {
//   var rest = this.slice((to || from) + 1 || this.length);
//   this.length = from < 0 ? this.length + from : from;
//   return this.push.apply(this, rest);
// };
/*
* GLOBALS
*/
var GLOBAL_EASING = 'easeInOutQuad';
var opacitySupport = $.support.opacity; //this is so we can do something else besides fades in IE cuz of it's abysmal handling of fading pngs

var triggerGAEvents = function (dataset){
	if(dataset.event == "_trackEvent"){// only trigger events
		//console.log(dataset + "\n" + dataset.event + "\n" + dataset.category + "\n" + dataset.action + "\n" + dataset.label);
		_gaq.push([dataset.event, dataset.category, dataset.action, dataset.label]); 		
	}
}

var getForm = function(theUrl, theForm, theType){
	var theData = theForm ? theForm.serialize(): false;
	var postType;
	var theSpinner = $("<div/>", {"class":"spinner dark"}).css({
		"display" : "none",
		"position" : "absolute",
		"top" : "50%",
		"left" : "50%",
		"zIndex" : '999'
	}).append($("<span/>")).appendTo('body');
	
	if(opacitySupport){
		theSpinner.clearQueue().hide().fadeIn(200);
	}else{
		theSpinner.show();
	}
	
	if(theType){
		postType = theType;
	}else{
		postType = 'GET';
	}	
	$.ajax({
		url: theUrl,
		dataType: 'html',
		type:postType,
		data:theData,
		success: function(data, textStatus, xhr){
			var theContent = $('.modal', data);
			var theWidth = 693;
			var trackingData = theContent.data("ga");
			
			if(theContent.length){//EVERYTHING WENT OK
				// if tracking form fire GA event, including validation errors, template is smart!
				if (theContent.data("ga")){triggerGAEvents(trackingData);} 
				
				if(theContent.hasClass('contact')){
					theWidth = 900;
				}else if(theContent.hasClass('emailForm')){
					theContent.find('textarea').text(document.location.href);
				}
			}else{//ERROR
				// if we're tracking form, if it's registration, fire error event
				if (theContent.data("ga")){
					if(trackingData.category == "Registration"){
						trackingData.label="Start: Form Retrieval Error";
						triggerGAEvents(trackingData);
					}
				} 
				theContent = $('<div class="modal regConfirm"><h2>'+ string_ERROR + '</h2><p>'+string_PROBLEM_COMPLETING_REQUEST+'</p></div>');
			}
			
            var theReply = theContent.buildOverlayGeneric({width:theWidth});
			if(theContent.find('form').length){
				theContent.find('form').validateForm({
					callback : function(){
						var thisForm = theContent.find('form');
						thisForm.find('input[type=submit]').attr('disabled', 'disabled').fadeTo(0, .5).addClass('disabled');
						if(thisForm.parent().hasClass('signIn')){
							thisForm.submit();
						}else{
							getForm(thisForm.attr('action'), thisForm, 'POST');
						}
					}
				});
			}
			if(opacitySupport){
				theSpinner.show().delay(10).fadeOut(200, function(){theSpinner.remove();});
			}else{
				theSpinner.remove();
			}
            theReply.open();
		},
		error: function(xhr, textStatus, errorThrown){
	  		console.log('ajax error: '+  errorThrown);
		}
	});
}
var initFormLinks = function(){
	$('a[href^="' + url_SIGNIN + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});
	
	$('a[href^="' + url_REGISTER + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});
	
	$('a[href^="' + url_WI_SUBSCRIBE + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});
	
	$('a[href^="' + url_CONTACT + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});
	
    // FIXME: The url /subscribe/ doesn't seem to exit on the site...
	$('a[href^="/subscribe/"]').live('click', function(e){
		e.preventDefault();
		getForm(url_WI_SUBSCRIBE);
	});
	
	$('a[href^="' + url_FORGOT_PASSWORD + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});

	$('a[href^="' + url_SHARE_EMAIL + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});
	
	$('a[href^="' + url_NEWSLETTER_SIGNUP + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});
}

var IwcToolTip = function(content, triggerElem, opts){
	var surrogate = this;
	var defaults = {
		wrapperClass : '',
		leftOffset: 15,
		dur : 200
	}
	this.opts = $.extend(defaults, opts);
	
	this.trig = $(triggerElem);
	this.cont = $(content);
	this.dom = $('<div/>', {'class':'toolTip '+this.opts.wrapperClass });
	this.shadowWrap = $('<div/>', {'class':'ttShadow'});
	this.shadowWrapR = $('<div/>', {'class':'ttShadowR'});
	
	// this.cont.detach();
	this.dom.html(this.cont).append(this.shadowWrap).append(this.shadowWrapR);
	
	var tthoverConfig = {
		interval:100,
		timeout:400,
		over:function(e){ surrogate.show(); },
		out:function(e){ return false; }
	}
	
	this.trig.hoverIntent(tthoverConfig);
	
	if(this.cont.find('.fb_like').length >= 1){
		this.cont.find('.fb_like').html('<iframe src="http://www.facebook.com/plugins/like.php?href='+ document.location.href +'&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=25" scrolling="no" frameborder="0" style="border:none; max-width:80px; margin:0 auto; height:25px;" allowTransparency="true"></iframe>')
	}
}
IwcToolTip.prototype.show = function(){
	var surrogate = this;
	
	target = {
		left:this.trig.offset().left,
		top:this.trig.offset().top
	}
	
	if(opacitySupport){
		this.dom.
			appendTo('body').
			css(target).
			css({marginTop:-this.dom.height() + 5, marginLeft:-this.dom.width()/2 + this.opts.leftOffset}).
			hide().
			animate({marginTop : '-=17px'}, {queue: false, duration:this.opts.dur}).
			fadeIn(this.opts.dur).
			mouseleave(function(){
				surrogate.hide();
			});
	}else{//IE
		this.dom.
			appendTo('body').
			css(target).
			css({marginTop:-this.dom.height() + 5, marginLeft:-this.dom.width()/2 + this.opts.leftOffset}).
			animate({marginTop : '-=17px'}, {queue: false, duration:this.opts.dur}).
			mouseleave(function(){
				surrogate.hide();
			});
	}

	
	this.trig.addClass('selected');
	this.shadowWrap.height(this.dom.height());
	this.shadowWrapR.height(this.dom.height());
}
IwcToolTip.prototype.hide = function(){
	var surrogate = this;
	if(opacitySupport){
		this.dom.animate({marginTop : '-=9px'}, {queue: false, duration:this.opts.dur}).fadeOut(this.opts.dur, function(){ surrogate.dom.remove();});
	}else{//IE
		this.dom.animate({marginTop : '-=9px'}, {queue: false, duration:this.opts.dur, complete:function(){ surrogate.dom.remove();}});
	}
	
	this.trig.removeClass('selected');
}

//simple bootstrapper for tabbed nav
$.fn.tabNav = function(){
	if(this.hasClass('profileTabs')){
		var pt = new ProfileTabs(this);
	}else{
		var tn = new TabNav(this);
	}
}

//basic IWC tabbed navigation
var TabNav = function(e){
	var surrogate = this;
	
	// props
	this.indicator = $('<div class="indicator" />');
	this.tabs = e.find('li');
	
	// event handlers
	this.tabs.bind('click', function(){ surrogate.select(this) });
	
	//go!
	e.append(this.indicator);
	this.select(this.tabs[0], true);
}
TabNav.prototype.select = function(tab, initial){
	var t = $(tab);
	var indicatorTarget = t.position().left + (t.width()/2 - this.indicator.width()/2);
	
	t.addClass('selected').siblings().removeClass('selected');
	if(initial){
		this.indicator.css({left:indicatorTarget});
	}else{
		this.indicator.animate({left:indicatorTarget});
	}
}

//profile form tabbed navigation
var ProfileTabs = function(e){
	TabNav.call(this, e);
	
	var surrogate = this;
	
	this.tabs.bind('click', function(){
		if(pfStateChanged == true){
			var conf = confirm(string_UNSAVED_CHANGES);
			if(conf){
				console.log($(this).find('a').attr('href').split('#')[1]);
				surrogate.switchContent('#' + $(this).find('a').attr('href').split('#')[1]);
			}
		}else{
			console.log($(this).find('a').attr('href').split('#')[1]);
			surrogate.switchContent('#' + $(this).find('a').attr('href').split('#')[1]);
		}
		return false;
	});
}
ProfileTabs.prototype = jQuery.extend({}, TabNav.prototype, ProfileTabs.prototype); //extending the TabNav to create ProfileTabs
ProfileTabs.prototype.switchContent = function(content){
	var formToShow = $(content + 'Wrap');
	var fWrap = $('#formWrap');
	var dur = 200;

	fWrap.height(fWrap.height());
	
	$('.formHolder').not(formToShow).fadeOut(dur, function(){
		formToShow.show().fadeTo(0,0).addClass('selected');
		fWrap.animate({height:formToShow.height()}, {duration:dur*2, complete:function(){
			formToShow.fadeTo(dur,1);
		}});
	}).removeClass('selected');

	pfStateChanged = false;
}

var pfStateChanged = false;
var ProfileForm = function(){
	var surrogate = this;
	var pForm = $('#profileForm');
	var fWrap = $('#formWrap');
    var formHolders = $('.formHolder');
	//var submits = fWrap.find('input.submit');
    var submits = formHolders.find('input.submit');
	var submitText = submits.text();
	var avatarLinks = pForm.find('.avatars li a');
	var avatarField = $('#id_avatar');
	var mwTable = $('#myWatches table');
	var mwRows = mwTable.find('tr').not(':first-child');
	var closeBtn = $('<td class="close"><img src="'+ MEDIA_URL + 'chrome/images/field_delete.png" /></td>');
	
	var initProfileEditForm = function(){
		//attaching the tooltips
		$('label span.description, .label span.description').each(function(){
			var trig = $('<span class="toolTipTrigger">?</span>')
			$(this).parent().append(trig);

			new IwcToolTip(this, trig.get(0));
		});

		//avatar links stuff
		avatarLinks.bind('click', function(e){
			e.preventDefault();
			var t = $(this);

			avatarLinks.not(t).removeClass('selected');
			t.addClass('selected');

			avatarField.val(t.attr('href').substring(1)); //set the field value
		});

		// myWatches form
		$('td.close').live('click', function(){ //delete row
			var sur = $(this);

			// PUT THE AJAX CALL TO REMOVE THE WATCH HERE, IF WE'RE NOT JUST DOING IT ON SAVE

			sur.parent().remove();

			mwRows = mwTable.find('tr').not(':first-child');//update the rows collection

			mwRows.each(function(i){ //rename the input fields to reflect the actual order
				var ins = $(this).find('input');
				$(ins[0]).attr({
					'id' : 'model' + i,
					'name' : 'model' + i
				});

				$(ins[1]).attr({
					'id' : 'caseNumber' + i,
					'name' : 'caseNumber' + i
				});
			});
		});

		$('#myWatchesWrap').find('a.add').bind('click', function(){ //add row
			mwRows = mwTable.find('tr').not(':first-child'); //update the rows collection

			var currRow = mwRows.length;
			var domString = '<tr><td>';
			domString += '<input name="model'+ currRow +'" id="model'+ currRow +'" class="text" type="text" />';
			domString += '</td><td>';
			domString += '<input name="caseNumber'+ currRow +'" id="caseNumber'+ currRow +'" class="text" type="text" />';
			domString += '</td>';
			$(domString).append(closeBtn.clone()).appendTo(mwTable);

			return false;
		});

		mwRows.append(closeBtn);
		
		// hide forms
		$('.formHolder').not('.selected').hide();

		fWrap.find('input, textarea, select').change(function(){ pfStateChanged = true });
		
		CustomForm.init();
		
		submits.bind('click', function(e){ //THIS IS WHERE WE'LL PUT THE AJAX FORM SUBMISSION FUNCTION
			e.preventDefault();
			var thisForm = $(this).closest('form');
			var theData = thisForm.serialize();
			var theUrl = thisForm.attr('action'); //this is the URL where we're sending the form
			thisForm.find('input[type=submit]').attr('disabled', 'disabled').fadeTo(0, .5).addClass('disabled').val(string_SAVING);
			
			$.ajax({
	 			url: theUrl,
	 			type: 'POST',
	 			data: theData,
	 			success: function(data) {
					var thisFormId = thisForm.attr('id');
					var receivedForm = $('#' + thisFormId, data);
					thisForm.html(receivedForm.html());
					
					initProfileEditForm();//re-initialize all if the form stuff
	 			},
	 			error: function() {
	 		 		console.log('xhr error');
	 			}
	 		});

			pfStateChanged = false;
			return false;
		}).removeAttr('disabled').fadeTo(0, 1).text(submitText);//reset submit buttons
	}
	initProfileEditForm();
}

var GalapagosForm = function(){
	var surrogate = this;
	var gForm = $('#galapagosForm');
	var fWrap = $('#formWrap');
	var formHolders = $('.formHolder');
	//var submits = fWrap.find('input.submit');
	var submits = formHolders.find('input.submit');
	var submitText = submits.text();
	
	var initGalapagosForm = function(){
		//attaching the tooltips
		$('label img.description, .label img.description,label span.description, .label span.description').each(function(){
			var trig = $('<span class="toolTipTrigger">?</span>&nsbp;')
			$(this).parent().append(trig);
			new IwcToolTip(this, trig.get(0),{wrapperClass:'galapagosTip'});
		});

		$('input.required').siblings('label').append('<span class="required">&#42;</span>');
		$('select.required').siblings('label').append('<span class="required">&#42;</span>');

	}
	initGalapagosForm();
}


var StickyFilter = function(e, opts){
	
	var t = $(e);
	var w = $(window);
	var targ;
	var tTop;
	var pTop;
	window.onscroll = function(){		
		tTop = t.offset().top;
		pTop = t.parent().offset().top;		
		if(w.scrollTop() > tTop){
			t.css({ 'position' : 'fixed'}).addClass('active');
		}else if(w.scrollTop() < pTop){
			t.css({'position' : 'absolute'}).removeClass('active');
		}
	};
}

var DetailSwitcher = function(){
	// QUICK FIX FOR MULTIPLE DETAIL SWAPS, needs cleanup/optimzation...
	var specLists = $('.details .specsList');
	var calibreSpec = $('.details .calibreSpec');
	var detailLists = $('.details .detailList');
	var frontBack = $('.viewer .frontBackWrap');
	if(!frontBack.find(".back").length) {
		frontBack.addClass("noBack");
	}
	
	var varLinks = $('.variations ul li');
	var listToShow1,listToShow2,listToShow3,listToShow4;
	
	detailLists.not('.selected').hide();
	$(frontBack[0]).addClass('selected');
	$(varLinks[0]).addClass('selected').css({paddingRight:5});
	if(calibreSpec.length >= 0){
		$(calibreSpec[0]).addClass('selected');
	}
	varLinks.bind('click', function(){
		var numClicked = varLinks.index(this);
		varLinks.not(this).removeClass('selected').animate({paddingRight:0}, {duration:100});
		$(this).addClass('selected').animate({paddingRight:5}, {duration:100});
		//var currentEls = "#specsList_" + varLinks.index(this) + ",#calibre_" + varLinks.index(this) + ",#detailList_" + varLinks.index(this) + ".#frontBack_" + varLinks.index(this);
		
		listToShow1 = $(specLists[numClicked]);
		listToShow2 = $(calibreSpec[numClicked]);
		listToShow3 = $(detailLists[numClicked]);
		listToShow4 = $(frontBack[numClicked]);
		
		//detailLists.not(listToShow).hide();
		$('.details .specsList,.details .calibreSpec,.details .detailList,').removeClass('selected').hide();
		$('.viewer .frontBackWrap').not(frontBack[numClicked]).removeClass('selected');
		
		// listToShow.show();
		listToShow1.addClass('selected').show();
		listToShow2.addClass('selected').show();
		listToShow3.addClass('selected').show();
		listToShow4.addClass('selected');
		
		return false;
	});
}

//search result filter
var SearchFilter = function(){
	var sf = $('#searchFilter');
	var as = sf.find('a');
	var rDiv = $('#results');
	var rl = $('#resultsList');
	var sResults = rl.children('li');
	var oPaddingTop = sResults.css('paddingTop');
	var oPaddingBottom = sResults.css('paddingBottom');
	var fResults;
	var dur = 500;
	
	rDiv.height(rDiv.height());
	
	
	sResults.each(function(){
		var t = $(this);
		t.data('oHeight', t.height());
	})
	
	as.bind('click', function(){
		var t = $(this);
		var cat = t.attr('href').substring(1);
		
		if(cat == 'all'){
			sResults.each(function(){
				var t = $(this);
				t.stop().animate({height:t.data('oHeight'), paddingTop:oPaddingTop, paddingBottom:oPaddingBottom, borderBottomWidth:1}, {duration:dur, easing:GLOBAL_EASING});
			});
		}else{
			sResults.stop().not('.'+ cat).animate({height:0, paddingTop:0, paddingBottom:0, borderBottomWidth:0}, {duration:dur, easing:GLOBAL_EASING});
			$('.'+ cat).each(function(){
				var t = $(this);
				t.stop().animate({height:t.data('oHeight'), paddingTop:oPaddingTop, paddingBottom:oPaddingBottom, borderBottomWidth:1}, {duration:dur, easing:GLOBAL_EASING});
			});
		}
		
		as.not(t).removeClass('selected');
		t.addClass('selected');
		return false;
	});
}

var ExperienceFilter = function(){
	var surrogate = this;
	this.af = $('.articleFilter');
	this.h = this.af.find('h6');
	this.al = $('.articleList ol li');
	this.featureLinks = $('.experiences_top a.go').not('.arrow');
	
	//event handlers
	this.af.find('li a').bind('click', function(e){
		e.preventDefault();
		$(this).parent().addClass('selected').siblings().removeClass('selected');
		var filterTerm = $(this).attr('href').substring(1);
		if(filterTerm == 'all'){
			surrogate.showAll();
		}else{
			surrogate.filterEm(filterTerm, $(this).text());
		}
		document.location.hash =  filterTerm;
	});
	
	this.featureLinks.bind('click', function(e){
		e.preventDefault();
		$.scrollTo('.articleList', {duration:200});
		
		var filterTerm = $(this).data('topic');
		var link = surrogate.af.find('a[href=#'+filterTerm +']');		
		console.log(surrogate.af.find('a[href=#'+filterTerm+']').length);
		
		surrogate.filterEm(filterTerm, link.text());
		
		document.location.hash =  filterTerm;
	});
	
	this.hashCheck();
}
ExperienceFilter.prototype.filterEm = function(filterTerm, text){
	this.al.not('.topic_' + filterTerm).hide()
	this.al.filter('.topic_' + filterTerm).show();
	this.h.text(text);
}
ExperienceFilter.prototype.hashCheck = function(){
	var hash = document.location.hash.substring(1);
	var link = this.af.find('a[href='+document.location.hash +']');
	link.parent().addClass('selected').siblings().removeClass('selected');
	if(this.al.filter('.topic_' + hash).length > 0 && hash != ''){
		this.filterEm(hash, link.text());
	}
}
ExperienceFilter.prototype.showAll = function(){
	this.h.text('All Articles');
	this.al = $('.articleList ol li').show();
}

//form validation
$.fn.validateForm = function(opts){
	var defaults = {
		callback : function(){
			this.submit();
			// console.log('default');
		}
	};
	var options = $.extend(defaults, opts);
	
	var isValid = false;
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; //regex
	var inputs = $(this.find('input.text, textarea'));
	var alertClass = '.formError'; //change this to the class of your alert field 
	var requiredText = string_FIELD_REQUIRED;
	var emailText = string_VALID_EMAIL;
	var validate = function(){
		for(var i = 0;i<inputs.length;i++){
			var inp = $(inputs[i]);
			if(inp.hasClass('required') && (inp.val() == '' || inp.val() == null)){ //required field
				showAlert(inp, requiredText);
			}else if(inp.hasClass('email') && !emailReg.test(inp.val())){ //email validation
				showAlert(inp, emailText);
			}else{
				clearAlert(inp);
			}
		}
		
		//if there are no invalid fields, submit that form!
		if(!inputs.hasClass('invalid')){
			// this is where we'll put in the ajax form submission
			options.callback();
		}
	}
	
	var showAlert = function(inp, txt){
		inp.addClass('invalid').siblings(alertClass).text(txt);
	}
	
	var clearAlert = function(inp){
		inp.removeClass('invalid').siblings(alertClass).text('');
	}
	
	//bind the click to the submit
	this.bind('submit', function(){ validate(); return false; })
}

var ProgressBar = function(target, options){
	// default options
	var defaults = {
		sections:6,
		handleColor:'#333',
		easingMethod: 'swing',
		dur:200
	};
	var options = $.extend(defaults, options);
	var indicator = $('<div class="progressIndicator"></div>');
	var currPercent = 0;
	var sectionLength = target.width()/options.sections;
	
	indicator.css({position:'absolute', top:0, left:0, height:target.height(), width:0, backgroundColor:options.handleColor});
	target.append(indicator);
	
	var step = function(){
		indicator.width(indicator.width()+1);
	};
	
	var setIndicator = function(x){
		indicator.width(x)
	}
	
	var stepTo = function(percent){
		indicator.animate({width : target.width() * percent}, { duration:options.dur, easing:options.easingMethod });
		currPercent = percent;
	};
	var getPercentage = function(){
		return Math.floor(indicator.width()/target.width() * 100);
	};
	
	var inSection = function(){
		return indicator.width()/sectionLength;
	}
	
	//public functions
	return {
		step:step,
		stepTo:stepTo,
		getPercentage:getPercentage,
		inSection:inSection,
		setIndicator:setIndicator
	}
}

var PackOverlay = function(e){
	var surrogate = this;
	
	this.psInfo = $(e);
	this.li = this.psInfo.parent();
	
	
	var hoverConfig = {
		interval:50,
		timeout:50,
		over:function(e){ surrogate.show(); },
		out:function(e){ return false; }
	}
	this.li.hoverIntent(hoverConfig);
	this.psInfo.detach();
}
PackOverlay.prototype.show = function(){
	var surrogate = this;
	this.targ = {
		x : this.li.offset().left - 80,
		y : this.li.offset().top - 128
	}
	this.psInfo.css({left :this.targ.x, top:this.targ.y}).
		appendTo('body').
		bind('mouseleave', function(){
			surrogate.hide();
		}).
		fadeIn(100);
}
PackOverlay.prototype.hide = function(){
	var surrogate = this;
	this.psInfo.fadeOut(100, function(){
		surrogate.psInfo.remove();
	});	
}

var DayNight = function(e){
	var dur = 400;
	var t = $(e);
	var dial = t.find('.dial');
	var dayDial = dial.find('.day');
	var nightDial = dial.find('.night');
	var clickText = t.find('span.click');
	var lightsText = t.find('span.lights');
	var dTextColor = '#79797a';
	var nextH = t.find('h5');
	var overlay = $('<div id="overlay_black" />');
	var glowers = $('<div id="glowers" />');
	var dnContent = t.find('.dnContent');
	var isDay = true;
	var dialIsAnimating = false;
	
	var to;
	t.append(glowers);
	dnContent.detach();
	
	dial.bind('click', function(){
		if(dialIsAnimating){return false;}
		
		dialIsAnimating = true;
		if(isDay){
			overlay.clearQueue().fadeTo(0, 0).css({zIndex:0, height:$('body').height()}).appendTo('body').fadeTo(dur, .9);
			dayDial.clearQueue().animate({rotate:110});
			nightDial.clearQueue().animate({rotate:110}, {duration:dur, queue:false, complete:function(){dialIsAnimating = false}}).fadeIn(dur);
			clickText.clearQueue().animate({color:'#5a5a5b'});
			nextH.clearQueue().animate({color:'#424242'});
			lightsText.clearQueue().animate({color:'#8c8d8e'}).html('Lights<br/>On');
			dnContent.hide().css({left:t.offset().left + t.width() + 20, top:t.offset().top + 25}).appendTo('body').clearQueue().delay(dur * 2).fadeIn(dur * 5);
			glowers.clearQueue().fadeIn(dur);
			isDay = false;
			$(document).bind('keydown', function(e){
				if(e.keyCode == 27){
					dial.click();
				}
			})
		}else{
			dnContent.clearQueue().fadeOut(dur, function(){ dnContent.remove();});
			overlay.clearQueue().fadeOut(dur, function(){overlay.remove(); });			
			dayDial.clearQueue().animate({rotate:0, queue:false});
			nightDial.clearQueue().animate({rotate:0}, {duration:dur, queue:false, complete:function(){dialIsAnimating = false}}).fadeOut(dur);
			clickText.clearQueue().animate({color:dTextColor});
			nextH.clearQueue().animate({color:'#373737'});
			lightsText.clearQueue().animate({color:dTextColor}).html(string_LIGHTS_OFF);
			glowers.clearQueue().fadeOut(dur);
			isDay = true;
			
			$(document).unbind('keydown');
		}

		return false;
	})
	

}

$.fn.iwcSlider = function(options) {
	
	// default options
	var defaults = {
		type:'detail',
		height:420,
		easingMethod :'swing',
		duration:300,
		speed: 30,
		progressHeight:6,
		timer:true
	};
	
	var options = $.extend(defaults, options);
	var surrogate = this;
	var wrap = $('<div class="iwcSlider '+ options.type +'"></div>');
	var textOverlay = $('<div class="textOverlay"></div>');
	var textTrack = $('<div class="textTrack"></div>');
	var imgHolder = $('<div class="imgHolder"></div>');
	var textHolder = $('<div class="textHolder"></div>');
	var progressBar = $('<div class="progressBar"></div>');
	var playPause = $('<div class="playPause"></div>');
	var indicator = $('<div class="indicator"></div>');
	var lis = $('li', this);
	var list = $(this.find('ul'));
	var imgs = lis.find('img');
	var liWidth = Math.floor(this.width()/lis.length);
	var textList = this.clone();
	var currIndex = 0;
	var headers = lis.find('h4');
	var titles = lis.find('h3');
	var hColor = $(headers[0]).css('color'); //initial header color
	var hHeight = 0; //header height
	var totalHeight;//total height of the slider module
	var timer; //timeout timer
	var pb; //progress bar
	var isPaused = false;
	var liHeight;
	
	//set dimensions, add dom elements, add event listeners
	var init = function(){
				
		//wrap the ul with the wrapper element
		surrogate.wrap(wrap);

		//set the image holder dimensions and 	
		imgHolder.width(surrogate.width()).height(options.height).html(imgs);
		
		//set the header positions and text
		headers.css({marginTop:options.height + options.progressHeight});

		switch(options.type){ // parse out the content to display
			case 'detail':
			for(var i = 0;i<lis.length;i++){
				var p = $(lis[i]).children('p');
				var a = $(lis[i]).children('p').children('a').detach();
				
				// NO caption 
				if (isBlank(p.html())){
					p.html(''); // don't display any overlay
				}else{
					p.html('<span>' + p.html() + '</span>').append(a);
				}
			}
			break;
			
			case 'family':
			for(var i = 0;i<lis.length;i++){
				var h = $(lis[i]).children('h4').text();
				var p = $(lis[i]).children('p');
				var a = $(lis[i]).children('p').children('a').detach();
				var aHref = a.attr("href");
				
				// clean this up
				// YES headline YES caption YES link				
				if ((!isBlank(h)) && (!isBlank(p.html())) && (!isBlank(aHref))){
					//console.log("//YES headline YES caption YES link")
					p.html('<span><strong>'+ h +' &mdash; </strong>' + p.html() + '</span>').append(a);
				}
				
				// YES headline NO caption YES link				
				if ((!isBlank(h)) && (isBlank(p.html())) && (!isBlank(aHref))){
					//console.log("// YES headline NO caption YES link")
					p.html('<span><strong>'+ h +'</strong>' + p.html() + '</span>').append(a);
				}
				
				// NO headline YES caption YES link
				if ((isBlank(h)) && (!isBlank(p.html())) && (!isBlank(aHref))){
					//console.log("// NO headline YES caption YES link")
					p.html('<span>' + p.html() + '</span>').append(a);
				}
		
				// NO headline NO caption 
				if ((isBlank(h)) && (isBlank(p.html()))){
					//console.log("// NO headline NO caption ")
					p.html(''); // don't display any overlay
				}
			}
			break;
			
			case 'homepage':
			for(var i = 0;i<lis.length;i++){
				var t = $(lis[i]).children('h3').text();
				var h = $(lis[i]).children('h4').text();
				var p = $(lis[i]).children('p');
				var tHtml = "";
				var hHtml = "";

				//p.html('<span class="title ' + $(lis[i]).children('h3')[0].className + '">'+ t + '</span><span class="main"><strong>'+ h +' </strong>' + p.html() + '</span>');
				if(t){tHtml = '<span class="title ' + $(lis[i]).children('h3')[0].className + '">'+ t + '</span>';}
				if(h){hHtml = '<span class="main"><strong>'+ h +' </strong>' + p.html() + '</span>';}
				p.html(tHtml + hHtml);

			}

			titles.hide();
			break;
		}
		
		headers.each(function(){
			var sur = $(this);
			var surHtml = '<span>0' + (headers.index(sur)+1) + '.</span>';
			if (options.type == "detail"){surHtml += sur.text();}
			
			sur.html(surHtml);
			
			if ($(sur).outerHeight() > hHeight){
				hHeight = $(sur).outerHeight(); //set the height
			}
		});

		//set progress bar and text holder positions
		var texts = lis.children('p').clone();
		texts.hide().appendTo(textHolder);
		
		lis.width(liWidth - 1).bind('click', function(e){onLiClick(e, this);}).children('p').remove();
		
		if(options.type != 'homepage'){
			textHolder.css({bottom:hHeight + options.progressHeight});
		}
		
		surrogate.before(imgHolder).after(textHolder); //set ul height, insert stuff
		
		textOverlay.width(liWidth).height(hHeight).insertBefore(surrogate); //text overlay
		progressBar.css({bottom:hHeight}).width(surrogate.width()).insertAfter(surrogate);
		pb = new ProgressBar(progressBar, {sections:lis.length, dur:options.duration, easingMethod:options.easingMethod, handleColor:'#000'});
		
		indicator.css({bottom:hHeight, left:liWidth/2}).insertAfter(progressBar);
		
		//temp fix: checks if there's no h4 value
		for(var i = 0;i<lis.length;i++){
			var liSur = $(lis[i]);
			if (options.type == "detail"){
				var hH4 = $(lis[i]).children('h4').html();
				var h4End = hH4.slice(-7);
				if (h4End = "</span>"){	$(lis[i]).children('h4').append("&nbsp;")}
			}
			if(liSur.height() > liHeight){liHeight = liSur.height();}
		}
		
		lis.append(playPause).css({"height":liHeight});

		//get it goin on		
		timerGo();
		highLight(0);
	}
	
	var isBlank = function (pString){
	    if (!pString || pString.length == 0) {return true;}
	    return !/[^\s]+/.test(pString); // non-white space character, faster (?) than a whitespace removal validation
	}
	
	var timerGo = function(){
		timer = setInterval(function(){
			pb.step();
			var indPos =  Math.floor(pb.inSection());
			if(indPos < lis.length){
				if(currIndex != indPos){
					currIndex = indPos;
					highLight(indPos);
				}
			}else{
				highLight(0);
				pb.setIndicator(0);
			}			
		},options.speed);
	}	
	
	var timerStop = function(){
		clearInterval(timer);
	}
	
	//list item click handler
	var onLiClick = function(e, t){
		if($(e.target).hasClass('playPause')){ //if the pause button is clicked
			if(isPaused){
				timerGo();
				isPaused = false;
				surrogate.find('.playPause').removeClass('play');
				
			}else{
				timerStop();
				isPaused = true;
				surrogate.find('.playPause').addClass('play');
				
			}
		}else{			
			var num = lis.index(t);
			highLight(num, true);		
			currIndex = num;
			timerStop();
		}
	}
		
	//show the image and animate the progress bar
	var highLight = function(num, clicked){
		var theLi = $(lis[num]);
		var theImg = $(imgs[num]);
		var theHeader = $(headers[num]);
		var theP = $(textHolder.find('p')[num]);
		var pauseBtn = theLi.find('.playPause');
		var indicatorTarget = theLi.position().left + theLi.width()/2 - indicator.width()/2;
		
		headers.not(headers[num]).animate({color:hColor});
		theP.fadeIn(options.duration).siblings('p').fadeOut(options.duration);
		
		surrogate.find('.playPause').not(pauseBtn).fadeOut();
		pauseBtn.fadeIn();
		
		theImg.css({'z-index':1}).fadeIn(options.duration * 1.5).siblings().css({'z-index':0}).fadeOut(options.duration);
		if(clicked){ 
			pb.stepTo(num/lis.length); //animate progress bar
		}
		
		theHeader.animate({color:'#000'});
		indicator.stop().animate({left : indicatorTarget}, {duration:options.duration, easing:options.easingMethod});
		
		// don't show text overlay when there's no content. 
		if(isBlank(theP.text())){
			theP.parent().css({'display':'none'});
		}else{
			theP.parent().css({'display':'block'});
		}
		
		textOverlay.stop().animate({left : theLi.position().left}, {duration:options.duration, easing:options.easingMethod, complete: function(){
				if(clicked && !isPaused){
					timerGo();
				}
			}
		});
	}

	//intialize!	
	init();

	return this.each(function(){});
}

$.fn.packSlider = function(options) {
	// default options
	var defaults = {
		speed:200,
		easingMethod : GLOBAL_EASING,
		limit:7,
		childElems:this.children('li')
	};
	var options = $.extend(defaults, options);
	
	var list = this;
	var wrap = $('<div class="packSlider"/>');
	var inner = $('<div class="inner"/>');
	var controlBox = $('<div class="controlBox"/>');
	var lArrow = $('<div class="lArrow"/>');
	var rArrow = $('<div class="rArrow"/>');
	var watches = options.childElems;
	var watchWidth;
	var tabLength = 10;
	
	lArrow.bind('click', function(){ onButtonClick('left'); } );
	rArrow.bind('click', function(){ onButtonClick('right'); }).addClass('on');
	controlBox.append(lArrow).append(rArrow);
	this.wrap(wrap).before(controlBox).wrap(inner);
	watchWidth = $(watches[0]).outerWidth(true);
	$(this.parent(".inner")).width(watchWidth * options.limit);
	this.width(watchWidth * watches.length);
	
	if($(this).find('h6').length == 1){
		$(this).find('h6').detach().addClass('detached').insertBefore(controlBox);
	}
	
	$('#psDrawer').height();
	
	var onButtonClick = function(dir){
		var scrollTarg;
		var fadeDur = options.speed;
		switch(dir){
			case 'right':
			scrollTarg = -(watches.length - options.limit) * watchWidth;
			rArrow.removeClass('on');
			lArrow.addClass('on');
			break;
			
			case 'left':
			scrollTarg = 0;
			lArrow.removeClass('on');
			rArrow.addClass('on');
			break;
		}
		list.animate({'margin-left': scrollTarg}, {duration:options.speed});
	}
}

$.fn.frontBackSlider = function(opts){	
	var defaults = {
		dur : 300,
		easing : GLOBAL_EASING
	};
	// var wrap = $('<div id="frontBack"></div>');
	var frontBackID = $(this).attr("id"); 
	var wrap = $('<div id="'+ frontBackID +'" class="frontBackWrap"></div>');	
	var options = $.extend(defaults, opts);
	var sur = this;
	var sliderWindow = $('<div class="sliderWindow"></div>');
	var handle = $('<div class="handle"></div>');
	var shadow = $('<div class="shadow"></div>');
	var controls = $('<div class="fbSliderControls"><a href="#back" class="first">'+string_VIEW_BACK+'</a><a href="#front" >'+string_VIEW_FRONT+'</a></div>');
	var frontBtn = controls.find('a[href$="#front"]');
	var backBtn = controls.find('a[href$="#back"]');
	var front = this.find('.front');
	var limitRight = 432;
	var half = limitRight/2;	
	var shW;
	var lineLength = function(x, y, x0, y0){
	    return Math.sqrt((x -= x0) * x + (y -= y0) * y);
	};
	
	this.wrap(wrap);
	if (this.find('li').length == 2){
		//.append(shadow)
		sliderWindow.append(handle).insertBefore(this);
		controls.insertAfter(this);
		shW = shadow.width();
		if(opacitySupport){
			shadow.css({opacity:.1});
		}else{
			shadow.hide();
		}
	}
		
	frontBtn.bind('click', function(){
		slideWindowTo(442);
		return false;
	});
	
	backBtn.bind('click', function(){
		slideWindowTo(handle.width() + 2);
		return false;
	});
	
	handle.
		bind('drag', function(e, d){
			var pX = d.offsetX - $('#' + frontBackID).offset().left;
			var realX = (pX + 30);
			var targX = Math.min( limitRight, Math.max( 32, realX) );
												
			sliderWindow.width(targX);
			front.width(targX - 15);
			if(opacitySupport){
				var tmp = lineLength(pX + 15, 0, half, 0);
				var shO = tmp/half;
				shadow.css({left:targX - shW, opacity:1 - shO});
			}
	});
	
	var slideWindowTo = function(x){
		sliderWindow.stop().animate({width:x}, {duration:options.dur, easing:options.easing});
		front.stop().animate({width:x - 15}, {duration:options.dur, easing:options.easing});
		
		var shoPac = 1 - (lineLength(x + 15, 0, half, 0)/half);
		
		if(opacitySupport){
			shadow.stop().fadeTo(options.dur/2, .1).animate({left:x - shW, opacity:0}, {duration:options.dur, easing:options.easing, queue: false});
		}
	}
	
	slideWindowTo(limitRight);
}

var packshotDrawer = function(){
	var endHeight = 370;
	var sliderHeight = 251; 
	var psDrawer = $('#psDrawer');
	
	if(psDrawer.find('.promos .packSlider').length >= 1){//Promo drawer dimensions
		console.log(psDrawer.find('.promos .packSlider').height());
		endHeight = 370;
	}else if(psDrawer.find('.packSlider').length >= 1){//pack slider drawer dimensions
		endHeight = 390;
	}
	
	var controls = $('.drawerButton');
	var controlClone = controls.clone();
	var isDown = false;
	var sldr = psDrawer.find('.packSlider');
	controlClone.insertBefore(psDrawer.children(':first-child'));
	var buttons = $('a[href="#drawerOpen"]');
	
	buttons.bind('click', function(){
		if(isDown == false){
			psDrawer.animate({ height:endHeight}).css({'border-bottom-width' : 1});
			sldr.animate({height:sliderHeight, paddingTop:50, paddingBottom:20});
			controls.fadeTo(200, 0);
			isDown = true;
		}else{
			psDrawer.animate({ height:0}).css({'border-bottom-width' : 0});
			sldr.animate({height:0, paddingTop:0, paddingBottom:0});
			controls.fadeTo(200, 1);
			isDown = false;
		}
		
		return false;
	});
}

$.fn.calibre2 = function(opts){
	//LOCAL VARS
	var defaults = {
		dur : 200
	}
	var options = $.extend(defaults, opts);
	var cParts = this.find('li');
	var	partsBox = $('<div id="calibrePartsBox"></div>');
	var washout = $('<li class="washout"></li>');
	var copyBox = $('<div class="calibreCopy"></div>');
	var prevNext = $('<p id="prevNext"><a href="#prev" class="prev">'+string_PREV+'</a><a href="#next" class="next">'+string_NEXT+'</a></p>');
	var copyList = cParts.find('p').clone();
	var currPart = 0;
	var prevPart = 0;
	var raphHolder = $('<div/>').attr({id:'raphHolder'});
	var bg = $('<div/>').attr({id:'cbg'});
	var paper;
	var animDur = 100;
	var lineStart = {x: 401, y: 741}
	var hoverConfig = {
		interval:50,
		timeout:200,
		over:function(){onPartOver(this)},
		out:function(){onPartOut(this)}
	}
	
	
	//EVENT HANDLERS
	var onPartOver = function(e){
		var part = $(e);
		fadeInPart(part);
	}
	
	var onPartOut = function(e){}
	
	var onPartClick = function(e){
		var ind = cParts.index(e);
		if(ind != currPart){
			showPartInfo(ind);
		}
	}
	
	var onPrevNextClick = function(e){
		var newPart;
		
		switch($(e.target).attr('href')){
			case '#prev':
			newPart = currPart - 1 > 0 ? currPart - 1 : 0;
			break;
			
			case '#next':
			newPart = currPart + 1 < cParts.length ? currPart + 1 : cParts.length - 1;
			break;
		}
		if($(e.target).hasClass('disabled') == false){
			showPartInfo(newPart);
			fadeInPart($(cParts.get(newPart)));
		}
	}
	
	// METHODS
	var showPartInfo = function(ind){
		var pToShow = $(copyList.get(ind));
		var yOffset = 0;
		var xOffset = 0;
		copyBox.attr('class', 'calibreCopy c_' + ind);
		copyList.hide().filter(pToShow).show();
		prevNext.show();
		switch(ind){
			case 0:
			yOffset = 20;
			xOffset = 20;
			break;
			
			case 1:
			yOffset = 10;
			xOffset = 0;
			break;
			
			case 2:
			yOffset = 10;
			xOffset = 40;
			break;
			
			case 3:
			yOffset = 30;
			xOffset = 10;
			break;
			
			case 4:
			yOffset = 40;
			xOffset = 30;
			break;
			
			case 5:
			yOffset = 50;
			xOffset = 33;
			break;
		}
		
		drawLine(lineStart.x, lineStart.y, $(cParts[ind]).position().left + xOffset, $(cParts[ind]).position().top + yOffset);
		
		currPart = ind;
		if(currPart == 0){
			$('#prevNext .prev').addClass('disabled');
		}else{
			$('#prevNext .prev').removeClass('disabled');
		}
		
		if(currPart >= cParts.length - 1){
			$('#prevNext .next').addClass('disabled');
		}else{
			$('#prevNext .next').removeClass('disabled');
		}
	}
	
	var drawLine = function(ox, oy, tx, ty){
		if($('#prevNext').hasClass('drawn') == false){
			$('#prevNext').addClass('drawn');
			$('#calibreContainer .pullQuote').hide();
		}
		paper.clear();
		var l = paper.path('M'+ ox + '  ' + oy);
		l.attr({
			stroke:'#a3443e',
			'stroke-width': '1px' 
		})
		var p1 = 'M'+ ox + ' ' + oy;
		var p2 = 'L'+ ox +' '+ (oy -20);
		var p3 = 'L1 '+ (oy - 20);
		var p4 = 'L1 '+ ty;
		var p5 = 'L'+ tx + ' ' + ty;
		l.animate({path:p1}, animDur, function(){
			l.animate({path:p1+p2}, animDur, function(){
				l.animate({path:p1+p2+p3}, animDur, function(){
					l.animate({path:p1+p2+p3+p4}, animDur, function(){
						l.animate({path:p1+p2+p3+p4+p5}, animDur);
					});
				});
			});
		}); 
	}
	
	var fadeInPart = function(part){
		cParts.stop().fadeTo(options.dur, 0).filter(part).fadeTo(options.dur, 1);
	}
	
	//SETUP - dom manipulation and event binding
	partsBox.bind('mouseenter', function(){
		washout.stop().fadeTo(options.dur, .6);
		// copyList.hide();
		 copyBox.fadeIn();
	}).bind('mouseleave', function(){
		washout.stop().fadeTo(options.dur, 0);
		cParts.stop().fadeTo(options.dur, 0);
		// copyBox.fadeOut();
	});
	
	this.addClass('initialized').wrap(partsBox);
	$('#prevNext .prev').addClass('disabled');
	washout.css({opacity:0}).appendTo(bg);
	
	copyList.hide();
	prevNext.find('a').bind('click', function(e){ onPrevNextClick(e); return false; });
	copyBox.append(prevNext).append(copyList).insertAfter(this).hide();
	bg.insertBefore(this);
	raphHolder.height(this.height()).insertBefore(this);
	paper = Raphael("raphHolder", raphHolder.width(), raphHolder.height());
	
	cParts.hoverIntent(hoverConfig).css({opacity:0}).bind('click', function(){
		onPartClick(this);
	}).each(function(i){
		$(this).addClass('c_part_' + i);
	});
	
	return this.each(function(){});
}

var paralaxBG = function(){//yes, i know that parallax is spelled wrong...
    var w = $(window);
    var b= $('body');
    w.scroll(function(){
        var bgTargY = - w.scrollTop()/4 + 350;
        var bgTarg = '50% ' + bgTargY + 'px';
        b.css('backgroundPosition', bgTarg);
    });
}

var equalizeColumns = function(){
	var rowsToEQ = $('#wrapper .row, .promos .row').not('.retail .row, .commentList, .intervention .details');
	var homeCols = $('.homeFirstCol, .homeSecondCol, .homeThirdCol');
	
	rowsToEQ.each(function(){
		var heights = [];
		var theCols = $(this).find('.col_4, .col_3, .col_8, .col_9');
		if(theCols.length > 1){
			theCols.each(function(){
				heights.push($(this).height());
			});
			theCols.height(Math.max.apply(Math, heights));
		}
	});
}

var formPlaceholderSetup = function(){
	$(".comments textarea, .commentsBox textarea, .commentsBox input.text, .commentsBox input[type=text]").each(function() {
		$(this).bind({
			focus: function(){
				// $("label", $(this).parent()).fadeOut(100);
				$("label[for='" + $(this).attr('id') + "']").fadeOut(100)
			},
			blur: function() {
				if ($(this).val() == ""){
					// $("label", $(this).parent()).fadeIn(100);
					$("label[for='" + $(this).attr('id') + "']").fadeIn(100)
				}
			}
		});
		if ($(this).val() != ""){
			$("label", $(this).parent()).hide();
		}
	});
}

var commentFieldSetup = function(){
	$('.comments textarea').bind('focus', function(){
		if($('.userHello').length < 1){
			getForm(url_REGISTER);
		}
	}).addClass('required');
	
	$('#commentPost').validateForm();
}

var forumLinksSetup = function(){
	$('.forum table tbody tr').each(function(){
		var theRow = $(this);
		$('td', this).live('click', function(){
			document.location = theRow.find('a').attr('href');
		});
	}).css({cursor:'pointer'});
}

var collectionLandingLinksSetup = function(){
	$('.collection .gallery .col.first .familyModule, .collection .gallery .col.last .familyModule').bind('click', function(){
		document.location = $(this).find('a').attr('href');
	});
}

var CommentExpando = function(el, theLimit){
	this.cList = $(el);
	this.limit = theLimit;
	this.lis = $('li', this.cList);
	this.button = $('a.viewAllComments');
	this.downText = 'Collapse Comments';
	this.upText = this.button.text();
			
	if(this.lis.length > this.limit){
		this.button.css({display:'block'});
		this.collapse();
	}
}
CommentExpando.prototype.collapse = function(){
	var surrogate = this;
	if(this.cList.hasClass('commentList')){
		// $.scrollTo('.comments');
	}
	
	this.lis.each(function(i){
		if(i>surrogate.limit-1){
			$(this).hide();
		}
	});
	
	this.button.bind('click', function(e){
		e.preventDefault();
		surrogate.expand();
	}).removeClass('down').find('span').text(this.upText);
}
CommentExpando.prototype.expand = function(){
	var surrogate = this;
	
	this.lis.show();
	
	this.button.bind('click', function(e){
		e.preventDefault();
		surrogate.collapse();
	}).addClass('down').find('span').text(this.downText);
}

var ShareBar = function() {
	
}

$.fn.shareBarInit = function() {
	var lo = 47
	$(this).each(function() {
		var t = $(this);
		$('a.sharePage').bind('click', function(){return false;})
		if(t.parent().hasClass('col_4')){
			lo = 12;
		}else if(t.closest('.actionBar').length > 0){
			lo = 17;
		}
		
		$('.fbLinks', this).each(function(){
			var targ = t.parent().find('.facebook');
			new IwcToolTip(this, targ, {wrapperClass:'share', leftOffset:lo});
		}).bind('click', function(e){e.preventDefault();});
		
		$('a.twitter', this).bind('click', function(e){
			e.preventDefault();
			var loc = window.location.href;
			var title  = document.title;
			window.open('http://twitter.com/share?url=' + loc + '&text=' + title, 'twitterWindow', 'height=450, width=550, top='+($(window).height()/2 - 225) +', left='+$(window).width()/2 +', toolbar=0, location=0, menubar=0, directories=0, scrollbars=0');
			return false;
		}).attr('href', '');
	
	});
}
$(document).ready(function() {
	if(!isIE6){//do these things if you're on a modern browser
		
		// homepage marquee 
		if($('.slider.homepage-marquee').length > 0){ $('.slider.homepage-marquee').iwcSlider({type:'homepage'}); }
        
		// family marquee 
		if($('.slider.family-marquee').length > 0){ $('.slider.family-marquee').iwcSlider({type:'family'}); }
		
		// detail marquee 
		if($('.slider.detail-marquee').length > 0){ $('.slider.detail-marquee').iwcSlider({type:'detail'}); }
		
		// front/back slider -
		$('.frontBack').each(function(){
			$(this).frontBackSlider();
		});

		// pack shot slider
		$('.pack_shots').each(function(){
			if($(this).children('li').length > 7){
				$(this).packSlider();
			}
		});
		
		$('.promos .row').each(function(){
			var elems = $(this).children('.col_3');
			if(elems.length > 4){
				$(this).packSlider({childElems:elems, limit:4});
			}
		});

		// detail viewer
		$(".variations ul").buildWatchDetail($(".enlarge"));

		// calibre
		if(document.getElementById('calibreParts')){
			$('#calibreParts').calibre2();
		}
		
		//paralax bg
		if($('body').hasClass('paralax')){
			paralaxBG();
		}
		
		if(document.getElementById('psDrawer')){
			packshotDrawer();
		}
		
		//tabbed nav
		if($('.tabs').length > 0 ){
			$('.tabs').tabNav();
		}
		
		//pack shots
		$('.psInfo').each(function(){
			new PackOverlay(this);
		});
		
		//day night
		$('.dayNight').each(function(){
			new DayNight(this);
		});
		
		if(document.getElementById('searchFilter')){
			// new SearchFilter();
		}
		
		if(document.getElementById('profileForm')){
			new ProfileForm();
		}
		
		if(document.getElementById('galapagosForm')){
			new GalapagosForm();
		}
		
		if($('.articleFilter').length > 0){
			$('.articleFilter .inner').each(function(){
				new StickyFilter(this);
			});
			
			new ExperienceFilter();
		}
		
		// trunc further exploration title				
		$('.psDrawer div.promo, .promos .promo, .promoModule .promo').not('#wrapper .promos .promo, .service .promos .promo').each(function(){
			//console.log("Is Title two lines? " + $(this).truncateBlockAtLine(2,"..."));
			//console.log("descTrunc is " + descTrunc);
			
			var lineHeight = parseInt($(this).find('h5').css("line-height")), ht = $(this).find('h5').height(), descTrunc;
			if(ht > lineHeight) {
				$(this).find('h5').truncateBlockAtLine(2,"...");
				descTrunc = 2;
			} else {
				descTrunc = 3;
			}
			//var descTrunc = $(this).find('h5').truncateBlockAtLine(2,"...") ? 2 : 3; // determine how many desc lines to keep
	
			// trunc desc
			var fullHref =	$(this).find("a").eq(0).attr("href");
			var appendix = "...&nbsp;<a>Read&nbsp;More</a>";
			
			$(this).find("p").html($(this).find("p").html()+appendix);
			$(this).find("p").truncateBlockAtLine(descTrunc, appendix); // trunc
			$(this).find("p").find("a").attr("href",fullHref);
		})				
						
		//section navigation for the manufacturing page and possibly others
		if($('#sectionNav').length > 0){
				var sn = $('#sectionNav');
				var as = sn.find('a');
				var anchors = $('a.anchor');
				var curContent;
				var prevContent;
				
				new StickyFilter(sn.children('ul'), {ot:1976});
				sn.localScroll({hash:true});
				
				as.bind('click', function(){
					$(this).addClass('selected');
					as.not(this).removeClass('selected');
				});
				
				$(window).bind('scroll', function(){//select the nav that's associated with the content in the viewport
					curContent = anchors.filter(':in-viewport').eq(0).attr('name');
					prevContent;
					if( curContent != undefined && curContent != prevContent){
						as.removeClass('selected').filter('a[href$="#'+curContent+'"]').addClass('selected');;
						
						prevContent = curContent;
						// console.log(curContent + ' ' + prevContent);
			
					}
				})
			}
		
		//watch detail switcher
		if($('.details .specsList').length >= 1){
			new DetailSwitcher();
		}
		
		//comments expando 
		if($('.comments .commentList').length == 1){
			new CommentExpando($('.commentList'), 10);
		}
		// 
		if($('.profile .subFooter .recentActivity').length == 1){
			new CommentExpando($('.profile .subFooter .recentActivity ul'), 5);
		}
	
		$('.indent p:first-child').prepend('<span class="indentRule"></span>');
		initFormLinks();//bind the form links for overlays
	}
	
	
	// Find GA event for non-xhr pages (activation pass/fail), right now assumes one per page
	if ($('.modal').data("ga")){triggerGAEvents($('.modal').data("ga"));}
	
	
	$(".shareBar").each(function(){
		$(this).shareBarInit();
	})
	
	commentFieldSetup();//launches reg form if you're not signed in and try to comment
	formPlaceholderSetup();//placeholder text hide/show for textfields
	$('a').newWin(); //open external links in new window
	forumLinksSetup();//open forum row links when clicking anywhere in the row
	collectionLandingLinksSetup();//open collection landing page links when clicked anywhere
});

$(window).load(function(){
	equalizeColumns();//EQ colum height after images load
})

// fixes all pngs on document ready
// $(function(){$(document).pngFix();});


// $.truncateWordAtWidth
// Truncates the single-word text contents (ineffective on elements that contain whitespace) of an element to not overflow beyond a certain width
// Can pass in an optional appendix (i.e. an ellipsis) to use with truncation
// Returns true is the block is truncated and false if it isn't.
$.fn.truncateWordAtWidth + function(desiredWd, appendix) {
	if($(this).find("*").length < 1 && $(this).text().length && $(this).text().indexOf(" ") == -1) {
		appendix = typeof appendix == "string" ? appendix : "";
		desiredWd = typeof desiredWd == "number" && desiredWd > 0 ? desiredWd : $(this).width();
		var txt = $(this).text();
		var temp = $(this).clone();
		$(this).replaceWith(temp);
		temp.wrapInner("<span/>");
		var curWd = temp.find("span").width();
		
		if(curWd > desiredWd) {
			var len = Math.floor(txt.length*(desiredWd/curWd));
			temp.find("span").empty().text(txt.substr(0, len)+appendix);
			while(temp.find("span").width() < desiredWd) {
				len++;
				temp.find("span").empty().text(txt.substr(0, len)+appendix);
			}
			while(temp.find("span").width() > desiredWd) {
				len--;
				temp.find("span").empty().text(txt.substr(0, len)+appendix);
			}
			$(this).text(temp.find("span").text());
			temp.replaceWith($(this));
			return true;
		} else {
			temp.replaceWith($(this));
			return false;
		}
	} else {
		return false;
	}
};


// $.truncateBlockAtLine
// Truncates the text and inline contents (ineffective on elements that contain block-level children) of an element to not overflow beyond a certain height
// Can pass in an optional appendix (i.e. an ellipsis) to use with truncation
// Returns true is the block is truncated and false if it isn't.
$.fn.truncateBlockAtLine = function(lines, appendix) {
	// Make sure this object is a has text and has no non-inline children
	if($(this).css("display")=="block" && $(this).html().length && !$(this).find("*").filter(function(){return $(this).css("display")!="inline";}).add("br").length) {
		appendix = typeof appendix == "string" ? appendix : "";
		lines = typeof lines == "number" && lines > 0 ? lines : 1;
		var fullHtml = this.html();
		var temp = this.clone();
		$(this).replaceWith(temp);
		
		var words = fullHtml.split(" ");
		var totalWords = words.length;
		var lineHeight = parseInt(temp.css("line-height"));
		var initialHeight = temp.height();
		var truncHeight = lineHeight*lines;
		var lineRatio = lines/(Math.floor(initialHeight/lineHeight));
		if(lineRatio < 1) {
			var sliceAt = Math.ceil(totalWords*lineRatio);
			do {
				var wordsSliced = words.slice(0,sliceAt++);
				temp.html(closeHtmlTags(wordsSliced.join(" ")+appendix));
			} while(Math.floor(temp.height()/parseInt(lineHeight)) <= lines);
			do {
				var wordsSliced = words.slice(0,sliceAt--);
				temp.html(closeHtmlTags(wordsSliced.join(" ")+appendix));
			} while(Math.floor(temp.height()/parseInt(lineHeight)) > lines);
			$(this).empty().html(closeHtmlTags(temp.html()));
			temp.replaceWith(this);
			return true;
		} else {
			temp.replaceWith(this);
			return false;
		}
	} else {
		return false;
	}
};


// $.truncateBlockAtHeight
// Truncates the contents of an element to not overflow beyond a certain height
// Can pass in an optional appendix (i.e. an ellipsis) to use with truncation
// Returns true is the block is truncated and false if it isn't.
$.fn.truncateBlockAtHeight = function(desiredHt, appendix) {
	if($(this).css("display")=="block" && $(this).html().length) {
		appendix = typeof appendix == "string" ? appendix : "";
		desiredHt = typeof desiredHt == "number" && desiredHt > 0 ? desiredHt : $(this).height();
		var fullHtml = this.html().replace(/<(?!meta\b)([\/]?)([a-z]+)([^>]*)?>/g, " <$1$2$3> ").replace(/(\r\n|\n|\r)/gm," ");
		var temp = this.clone();
		temp.wrapInner("<div/>");
		$(this).replaceWith(temp);
		
		var words = fullHtml.split(" ");
		var totalWords = words.length;
		var curHt = temp.children("div").eq(0).height();
		if(desiredHt < curHt) {
			var tempDiv = temp.children("div").eq(0);
			var sliceAt = Math.ceil(totalWords*(desiredHt/curHt));
			do {
				var wordsSliced = words.slice(0,sliceAt++);
				tempDiv.html(closeHtmlTags(wordsSliced.join(" ")+appendix));
			} while(tempDiv.height() <= desiredHt);
			do {
				var wordsSliced = words.slice(0,sliceAt--);
				tempDiv.html(closeHtmlTags(wordsSliced.join(" ")+appendix));
			} while(tempDiv.height() > desiredHt);
			$(this).empty().html(closeHtmlTags(tempDiv.html()));
			temp.replaceWith(this);
			return true;
		} else {
			temp.replaceWith(this);
			return false;
		}
	} else {
		return false;
	}
};


// --- Additional Functions ---

// closeHtmlTags
// Takes a string of HTML and ensures that all of its tags are properly closed.
function closeHtmlTags(html) {
	var tagRgx=new RegExp("<(?!meta|img|br|hr|input\b)([/]?)([a-z]+)([^>]*)?>","i"),openTags=[],strPieces=[],workStr=html,tagMatch,lastTag;
	while(tagMatch=tagRgx.exec(workStr)) {
		strPieces.push(workStr.substr(0,tagMatch.index));
		workStr=workStr.substr(tagMatch.index+tagMatch[0].length);
		if(tagMatch[1]!="/") {
			openTags.push(tagMatch[2]);
			strPieces.push(tagMatch[0]);
		} else {
			while(openTags.length>0) {
				t=openTags.length-1;
				lastTag=openTags.pop();
				strPieces.push("</"+lastTag+">");
				if(lastTag==tagMatch[2]){break;}
			}
		}
	}
	strPieces.push(workStr);
	return strPieces.join("");
}

// --- OVERLAY ---
$.fn.extend({
	buildOverlayGeneric : function(opts) {
		$('.overlay').remove();
		var controller = $(this).buildOverlay(opts);
		
		// Logic		
		return controller;
	},
	buildOverlayContact : function() {
		
		$('.overlay').remove();
		
		var controller = $(this).buildOverlay({width:"900"});
		
		// Logic		
		return controller;
	},
	buildOverlay : function(opts) {
		var defaults = {width:693}
		var options = $.extend(defaults, opts);
		
		$(this).detach();
		var controller = new OverlayWindow($(this), $(this).attr("id"), $(this).attr("id"), { width:options.width });
		
		// League of shadows
		// $("<div/>", {"class":"shadow-top"}).insertBefore(controller.$elmts.contents);
		// $("<div/>", {"class":"shadow-bottom"}).insertAfter(controller.$elmts.contents);
		// controller.$elmts.contents.wrap(
		// 	$("<div/>", {"class":"shadow-middle"})
		// );
		// $("div.shadow-middle", controller.$elmts.popover).append($("<div/>", {"class":"shadow-middle-top"})).append($("<div/>", {"class":"shadow-middle-bottom"}));
		
		// Close button
		$("<img/>", {
			"class" : "button closeButton",
			"src" : MEDIA_URL + "chrome/images/overlay_close_btn.png",
			"alt" : "Close",
			"click" : function(e) {
				e.preventDefault();
				controller.close();
			}
		}).prependTo(controller.$elmts.popover);
		controller.$elmts.contents.find('.closeForm, .closeModal').bind('click', function(e){
			e.preventDefault();
			controller.close();
		});
		return controller;
	}
});

function OverlayWindow(jqContents, id, hash, options) {
	var surrogate = this;
	
	var defaults = {
		fadeDur : 180, // 0 for no animation
		preloadContents : true,
		width : "auto",
		height : "auto"
	};
	$.extend(true, this, defaults, options);
	// this.id = id.toLowerCase();
	// this.hash = typeof hash != "undefined" ? hash.toLowerCase() : this.id;
	
	this.scrollable = false;
	
	this.$elmts = {};
	this.$elmts.overlay = $("<div/>", {"class":"overlay"}).css({
		"display" : "none",
		"position" : "fixed",
		"top" : 0,
		"left" : 0,
		"height" : $('body').height(),
		"width" : "100%",
		"zIndex" : 500
	}).appendTo("body").data("controller", this);
	this.$elmts.popover = $("<div/>", {"class":"popover"}).css({
		"display" : "block",
		"position" : "relative",
		"width" : this.width,
		"height" : this.height,
		"margin" : "0 auto"
	});
	if(this.width) this.$elmts.popover.width(this.width);
	if(this.height) this.$elmts.popover.height(this.height);
	this.$elmts.spinner = $("<span/>", {"class":"spinner","text":string_LOADING});
	this.$elmts.contents = $(jqContents).appendTo(this.$elmts.popover).css({"display":"block"});
	
	// this.hashCheck();
}
OverlayWindow.prototype.open = function() {
	var surrogate = this;
	
	// window.location.hash = "#"+this.hash;
	
	var images = [];
	$("img", this.$elmts.contents).each(function() { images.push($(this).attr("src")); });
	
	if(this.preloadContents && jQuery.loadImages && images.length) {
		this.$elmts.spinner.appendTo(this.$elmts.overlay);
		this.$elmts.overlay.fadeIn(this.fadeDur);
		
		$.loadImages(images, function() {
			// Hide spinner
			surrogate.$elmts.spinner.detach();
			if(surrogate.fadeDur) {
				surrogate.$elmts.popover.appendTo(surrogate.$elmts.overlay).hide().fadeIn(surrogate.fadeDur);
			} else {
				surrogate.$elmts.popover.appendTo(surrogate.$elmts.overlay);
			}
			surrogate.updatePosition();
		});
	} else {
		this.$elmts.popover.appendTo(this.$elmts.overlay);
		this.$elmts.overlay.fadeIn(this.fadeDur);
		surrogate.updatePosition();
	}
	
	$(window).bind("resize.popover", function() { surrogate.updatePosition(); });
	
	// fire the custom form element styler (see bundle), if it's there
	if(CustomForm.init){
		CustomForm.init();
	}
}
OverlayWindow.prototype.close = function() {
	var surrogate = this;
	
	// Setting the hash to "#" makes the page jump to the top
	// By measuring the overlay's y offset first, we can jump right back to where we were.
	// var top = this.$elmts.overlay.offset().top;
	// window.location.hash = "";
	// $.scrollTo(top);
	
	if(this.fadeDur) {
			this.$elmts.overlay.fadeOut(this.fadeDur, function() {
				surrogate.$elmts.spinner.detach();
				surrogate.$elmts.popover.detach();
			});
	} else {
		this.$elmts.spinner.detach();
		this.$elmts.popover.detach();
		$(window).unbind("resize.popover");
	}

}
OverlayWindow.prototype.updatePosition = function() {
	var surrogate = this;
	
	var htDiff = $(window).height() - this.$elmts.popover.height();
	if(htDiff > 0) {
		if(this.scrollable) {
			this.scrollable = false;
			$(window).unbind("scroll.popover");
		}
		this.$elmts.popover.css({"top" : htDiff/2});
	} else {
		if(!this.scrollable) {
			this.scrollable = true;
			this.overlayTop = this.$elmts.overlay.offset().top;
			$(window).bind("scroll.popover", function() {
				var topDiff = surrogate.overlayTop - surrogate.$elmts.overlay.offset().top;
				surrogate.overlayTop = surrogate.$elmts.overlay.offset().top;
				surrogate._scroll(topDiff);
			});
		}
	}
}
OverlayWindow.prototype._scroll = function(delta) {
	var diff = $(window).height() - this.$elmts.popover.outerHeight();
	var newTop =  this.$elmts.popover.position().top + delta;
	if(newTop > 0) {
		newTop = 0;
	} else if(newTop < diff) {
		newTop = diff;
	}
	this.$elmts.popover.css({"top" : newTop});
}
OverlayWindow.prototype.hashCheck = function() {
	var surrogate = this;
	
	var nowHash = window.location.hash.substr(1);
	if(this.hash == nowHash) {
		this.open();
	}
}

// --- IWC NAV 2: ELECTRIC BOOGALOO
var IwcNav2 = function(opts){
	var surrogate = this;
	this.defaults = {
		navRef : null,
		dur : 400,
		easingMethod : GLOBAL_EASING
	};
	this.nav = $('#pageHeader').find('.nav');
	this.dds = this.nav.find('.dd');
	this.ddLs = this.dds.parent();
	this.drawer = $('<div id="ddDrawer"></div>');
	this.indicatorTrack = $('<div class="indicatorTrack"></div>');
	this.indicator = $('<div class="indicator"></div>');
	this.isDrawerDown = false;
	this.iMoving = false;
	this.isOverLink = false;
	this.options = $.extend(this.defaults, opts);
	this.nav = $('#pageHeader').find('.nav');
	this.searchForm = this.nav.find('li.navSearch');
	this.searchField = this.searchForm.find('input.text');
	this.sfWidth = 140;
	this.optTrigger = this.searchForm.find('.optionTrigger');
	this.searchDD = this.searchForm.find('.searchOptions');
	this.optsList = this.searchDD.find('ul');
	this.isDrawerDown = false;
	this.isOverLink = false;
	
	// MAIN SETUP
	this.indicatorTrack.append(this.indicator);
	this.drawer.append(this.indicatorTrack).insertAfter(this.nav);
	
	this.drawer.bind('mouseleave', function(){
		if(!this.isOverLink){
			surrogate.hideDrawer();
		}
	});
	
	//highlight the proper nav element
	var loc = document.location.pathname.split('/')[1];
	if(loc == 'news' || loc =='library'){
		loc = 'about'
	}else if(loc == 'service'){
		loc = 'retail'
	}
	$('#topNav > li > a').not('[href="/' + loc +'/"]').parent().removeClass('active').end().end().filter('[href="/' + loc +'/"]').parent().addClass('active');
	
	// DD SETUPS
	var hoverConfig = {
		interval:this.options.dur/2,
		timeout:this.options.dur,
		over:function(){ddOver(this)},
		out:function(){ddOff(this)}
	}
	var ddOver = function(elem){
		var elem = $(elem);
		var theDD = $(elem).children('.dd');
		var theA = elem.children('a:first-child');
		var drawerMode = surrogate.isDrawerDown == true ? 'fade' : 'slide';
		if(!opacitySupport){//Why IE?? WHY YOU SO BAD AT ALPHA TRANSPARENCY??
			drawerMode = 'ie';
		}
				
		surrogate.showDropDown(theDD, { mode: drawerMode });
		var theHeight =  theDD.children().outerHeight();
		// if(theDD.hasClass('collection')){
		// 	theHeight = 330;
		// }
		var targX = theA.outerWidth()/2 + elem.position().left + 4;
		// console.log(theA.offset().left);
		surrogate.showDrawer(theHeight, targX);
	}
	var ddOff = function(elem){
		surrogate.hideDropDown($(elem).children('.dd'));
		if(!surrogate.isOverLink){
			surrogate.hideDrawer();
		}
	}
	this.ddLs.each(function(){
		$(this).hoverIntent(hoverConfig);
	}).addClass('ddLink').bind("mouseenter", function(){
		surrogate.isOverLink = true;
	}).bind("mouseleave", function(){
		surrogate.isOverLink = false;
	});
	
	this.dds.each(function(){
		var t = $(this);
		if(t.hasClass('collection')){
			t.children().wrapAll('<div class="inner"/>');
		}
		
		t.css({visibility:'visible'}).children().css({marginTop: -t.height()});
		
		if(t.hasClass('userInfo')){
			t.css({left: -t.parent().position().left, top:t.parent().position().top + t.parent().height()});
		}
	});
	
	// SEARCH SETUP
	var hoverConfigSearch = {
		interval:100,
		timeout:400,
		over:function(){surrogate.searchOver()},
		out:function(){surrogate.searchOut()}
	}
	this.searchForm.hoverIntent(hoverConfigSearch);
	this.searchField.width(0);
	this.optsList.show().css({marginTop: -(this.optsList.height() + 22) }).delegate('a', 'click', function(e){
		surrogate.searchOptionsClick(e);
		return false;
	}).hide();
	this.optTrigger.css({right:5}).bind('click', function(){
		$(this).addClass('active');
		surrogate.optsList.show().animate({marginTop:0}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod});
		return false;
	});
}
IwcNav2.prototype.showDropDown = function(dd, opts){
	var surrogate = this;
	var defaults = { mode : 'slide' };
	var opts = $.extend(defaults, opts);
	var theCont = dd.children();
	
	if(opts.mode == 'fade'){
		this.dds.children().not(theCont).each(function(){
			var t = $(this);
			t.fadeTo(surrogate.options.dur/3, 0, function(){t.hide()});
		});
		theCont.hide().delay(surrogate.options.dur).css({marginTop:0}).fadeTo(surrogate.options.dur/2, 1).addClass('active');
	}else if(opts.mode =="ie"){//sigh...
		this.dds.children().not(theCont).each(function(){
			var t = $(this);
			t.animate({marginTop: -t.outerHeight()}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod, complete:function(){t.hide()}});
		});
		theCont.show().css({marginTop:-theCont.outerHeight()}).animate({marginTop: 0}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod}).addClass('active');
	}else{
		theCont.show().fadeTo(0,1).css({marginTop:-theCont.outerHeight()}).animate({marginTop: 0}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod}).addClass('active');
	}
	
	// TODO:fix bg arrow for IE
	if(opts.mode !="ie"){
		dd.siblings('a').animate({backgroundPosition : '50% 50px'}, {duration:surrogate.options.dur/2, easing:surrogate.options.easingMethod});
	}
}

IwcNav2.prototype.hideDropDown = function(dd, opts){
	var surrogate = this;
	var defaults = { mode : 'slide' };
	var opts = $.extend(defaults, opts);
	
	// TODO:fix bg for IE
	if(opacitySupport){
		dd.siblings('a').stop().delay(surrogate.options.dur/2).animate({backgroundPosition : '50% 36px'}, {duration:surrogate.options.dur/2, easing:surrogate.options.easingMethod});
	}
}
IwcNav2.prototype.showDrawer = function(ht, indicatorX){
	var surrogate = this;
	if(!this.isDrawerDown){this.indicator.css({top:-10, left:indicatorX});}
	this.indicator.animate({top:0, left: indicatorX}, {duration:surrogate.options.dur/1.5, easing:surrogate.options.easingMethod});
	this.drawer.stop().animate({height:ht}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod, complete: function(){ surrogate.isDrawerDown = true; }});
}
IwcNav2.prototype.hideDrawer = function(){
	var surrogate = this;
	this.indicator.stop().animate({top:-10}, {duration:surrogate.options.dur/1.5, easing:surrogate.options.easingMethod});
	this.drawer.stop().animate({height:0}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod, complete: function(){ surrogate.isDrawerDown = false; }});
	this.dds.children().each(function(){
		$(this).animate({marginTop:-$(this).outerHeight()}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod, queue:false});
	});
}

IwcNav2.prototype.searchOver = function(){
	this.searchField.animate({width:140}, {duration:this.options.dur, easing:this.options.easingMethod}).focus();
	this.optTrigger.animate({right:175}, {duration:this.options.dur, easing:this.options.easingMethod});
}
IwcNav2.prototype.searchOut = function(){
	var surrogate = this;
	this.optsList.animate({marginTop: -(surrogate.optsList.height() + 22) }, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod, complete:function(){
		surrogate.searchField.animate({width:0}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod}).blur();
		surrogate.optTrigger.animate({right:0}, {duration:surrogate.options.dur, easing:surrogate.options.easingMethod}).removeClass('active');
		surrogate.optsList.hide();
	}});
	
}
IwcNav2.prototype.searchOptionsClick = function(e){
	var t = $(e.target);
	t.addClass('selected').parent().siblings().find('a').removeClass('selected');
	$('#id_filter').val(t.attr('href').substring(1));
	
	if(this.searchField.val() != ''){
		this.searchForm.find('form').find('.submit').click();
	}
}

var setupL10n = function(){
	var link = $('#topNav li#l10n');
	var dd = link.find('ul');
	dd.show();
	var ht = dd.outerHeight();
	dd.hide().css({'marginTop':-ht}).show();
	
	link.hoverIntent({
		over: function(){
			dd.stop().animate({'marginTop':0}, 300);
		},
		out: function(){
			dd.stop().animate({'marginTop':-ht}, 300);
		},
		timeout:200
	});
}

$(document).ready(function() {
	var nav = new IwcNav2();
	setupL10n();
});



// --- WATCH DETAIL VIEWER ---
function WatchDetail(data) {
	var surrogate = this;
	
	var properties = {
		variations : data,
		currentVariation : 0,
		currentZoomLevel : 1,
		frontBack : "front",
		isOpen : false,
		menuScrollable : false,
		instructionsShown : false
	}
	$.extend(this, properties);
	
	this.$elmts = {};
	
	this.$elmts.watchDetail = $("<div/>", {"class":"watchDetail"}).css({
		"position" : "fixed",
		"top" : 0,
		"left" : 0,
		"zIndex" : 500,
		"opacity" : 0
	}).width($(window).width()-20).height($(window).height()-20);
	
	this.$elmts.window = $("<div/>", {"class":"window"}).css({
		"position" : "absolute",
		"top" : 0,
		"left" : 0,
		"width" : "100%",
		"height" : "100%"
	}).appendTo(this.$elmts.watchDetail);
	
	this.$elmts.imageContainer = $("<div/>", {"class":"imageContainer"}).css({
		"position" : "absolute",
		"top" : 0,
		"left" : 0,
		"width" : "100%",
		"height" : "100%"
	}).appendTo(this.$elmts.window);
	
	this.$elmts.spinner = $("<div/>", {"class":"spinner"}).css({
		"display" : "none",
		"position" : "absolute",
		"top" : "50%",
		"left" : "50%"
	}).append($("<span/>")).appendTo(this.$elmts.window);
	
	this.$elmts.instructions = $("<div/>", {
		"class" : "instructions",
		"click" : function() {
				if(!surrogate.instructionsShown) {
					$(this).fadeOut(500, function() {
						$(this).detach();
						surrogate.instructionsShown = true;
					});
				}
			}
	}).css({
		"display" : "none",
		"position" : "absolute",
		"top" : 0,
		"left" : 0,
		"width" : "100%",
		"height" : "100%"
	}).append(
		$('<div/>').css({
			"position" : "relative",
			"top" : "50%",
			"left" : "50%"
		}).append(
			$("<h4/>", {"text":string_IMAGE_VIEWER})
		).append(
			$("<h2/>", {"html":string_CLICK_DRAG_EXPLORE})
		).append(
			$("<h3/>", {"html":string_VIEWER_INSTRUCTIONS})
		)
	);
	
	this.$elmts.image = null;
	
	this._buildMenuElmts();
	
	
	var hashObj = this._hashCheck();
	if(hashObj !== false) {
		this.setVariation(hashObj.variation);
		this.setFrontBack(hashObj.frontBack);
		this.setZoomLevel(hashObj.zoomLevel);
		this.open();
	}
};
WatchDetail.prototype.open = function() {
	if(!this.isOpen) {
		var surrogate = this;
		this.isOpen = true;
		
		var thumbUrls = [];
		for(var t=0; t<this.variations.length; t++) {
			thumbUrls.push(this.variations[t].thumbnail);
		}
		$.loadImages(thumbUrls, function() {
			
			$("html").css({
				width : "100%",
				height : "100%",
				overflow : "hidden"
			});
			surrogate.$elmts.watchDetail.appendTo("body");
			
			$(window).bind("resize.watchDetail", function() { surrogate._updateWindow(); });
			surrogate._updateWindow();
			
			if(!surrogate.instructionsShown) {
				surrogate.$elmts.instructions.insertBefore(surrogate.$elmts._menu.container).show();
			}
			surrogate.$elmts.watchDetail.fadeTo(300, 1, function() {
				if(!surrogate.instructionsShown) {
					setTimeout(function() {
						if(!surrogate.instructionsShown) {
							surrogate.$elmts.instructions.fadeOut(500, function() {
								$(this).detach();
								surrogate.instructionsShown = true;
							});
						}
					}, 5000);
				}
			});
			
			surrogate._selectImage(surrogate.currentVariation, surrogate.frontBack, surrogate.currentZoomLevel);
			
			// Bind movement stuff
			surrogate.$elmts.imageContainer.bind("mousedown", function(e) {
				e.preventDefault();
				surrogate.$elmts.image.stop();
				var restTimeout, oldX, oldY, evX, evY, deltaX, deltaY, updateCounter=0;
				var imageWd = surrogate.$elmts.image.width(), imageHt = surrogate.$elmts.image.height(), windowWd = $(window).width(), windowHt = $(window).height();
				var lowerLimitX = windowWd-imageWd, lowerLimitY = windowHt-imageHt;
				
				updateEventCoords(e);
				
				$(this).bind({
					"mousemove" : function(e) {
							clearTimeout(restTimeout);
							updateEventCoords(e);
							
							var pos = surrogate.$elmts.image.position();
							
							if(imageWd > windowWd) {
								var newLeft = pos.left + deltaX;
								if(newLeft > 0) {
									newLeft = 0;
								} else if(newLeft < lowerLimitX) {
									newLeft = lowerLimitX;
								}
							} else {
								newLeft = (windowWd-imageWd)/2;
							}
							
							if(imageHt > windowHt) {
								var newTop = pos.top + deltaY;
								if(newTop > 0) {
									newTop = 0;
								} else if(newTop < lowerLimitY) {
									newTop = lowerLimitY;
								}
							} else {
								newTop = (windowHt-imageHt)/2;
							}
							surrogate.$elmts.image.css({left:newLeft,top:newTop});
							restTimeout = setTimeout(function() { updateEventCoords(e); }, 100);
						},
					"mouseup" : function(e) {
							if(updateCounter > 2) {
								var n, distance, pos, newLeft, newTop;
								n = 8;
								distance = n*Math.sqrt(
									((oldX-evX)*(oldX-evX))
									+
									((oldY-evY)*(oldY-evY))
								);
								
								pos = surrogate.$elmts.image.position();
								if(imageWd > windowWd) {
									newLeft = pos.left + (deltaX*n);
									if(newLeft > 0) {
										newLeft = 0;
									} else if(newLeft < lowerLimitX) {
										newLeft = lowerLimitX;
									}
								} else {
									newLeft = (windowWd-imageWd)/2;
								}
								
								if(imageHt > windowHt) {
									newTop = pos.top + (deltaY*n);
									if(newTop > 0) {
										newTop = 0;
									} else if(newTop < lowerLimitY) {
										newTop = lowerLimitY;
									}
								} else {
									newTop = (windowHt-imageHt)/2;
								}
								if(imageWd <= windowWd && imageHt <= windowHt) {
									surrogate.$elmts.image.removeClass("movable");	
								} else {
									surrogate.$elmts.image.addClass("movable");
								}
								surrogate.$elmts.image.animate({"left":newLeft,"top":newTop}, Math.round(distance*.8), "easeOutQuad");
								
							}
							$(this).unbind("mousemove mouseup");
						},
					"mouseout" : function() {
							surrogate.$elmts.imageContainer.trigger("mouseup");
						}
				});
				
				function updateEventCoords(evt) {
					oldX = typeof evX == "number" ? evX : 0;
					oldY = typeof evY == "number" ? evY : 0;
					if(evt.pageX) {
						evX = evt.pageX;
						evY = evt.pageY;
					} else {
						evX = oldX;
						evY = oldX;
					}
					deltaX = evX-oldX;
					deltaY = evY-oldY;
					updateCounter++;
				}
			});
		}, false);
		
		$(document).bind("keyup.watchDetail", function(e) {
			if((typeof e.keyCode == "number" ? e.keyCode : e.which) == G_KEYCODES.esc) {
				surrogate.close();
			}
		});
	}
	
	return this;
};
WatchDetail.prototype.close = function() {
	if(this.isOpen) {
		var surrogate = this;
		
		this.$elmts.imageContainer.unbind("mousedown mousemove mouseup mouseout");
		$(document).unbind("keyup.watchDetail");
		
		
		var top = this.$elmts.window.offset().top;
		window.location.hash = "";
		if($.scrollTo) { $.scrollTo(top); }
		
		this.$elmts.watchDetail.fadeTo(300, 0, function() {
			surrogate.$elmts.instructions.detach();
			surrogate.$elmts.watchDetail.detach();
			
			$("html").css({
				width : "auto",
				height : "auto",
				overflow : "auto"
			});
			
			$(window).unbind("resize.watchDetail");
			surrogate.isOpen = false;
		});
	}
	return this;
};
WatchDetail.prototype.setVariation = function(index) {
	var newVariation, prevVariation = this.currentVariation;
	if(typeof index == "number") {
		if(index < 0) {
			newVariation = 0;
		} else if(index > this.variations.length) {
			newVariation = this.variations.length-1;
		} else {
			newVariation = index;
		}
	} else {
		newVariation = 0;
	}
	this.$elmts._menu._thumbnails[prevVariation].removeClass("selected");
	this.$elmts._menu._thumbnails[newVariation].addClass("selected");
	
	this.currentVariation = newVariation;
	
	return this;
};
WatchDetail.prototype.setFrontBack = function(state) {
	this.frontBack = (state == "back") ? "back" : "front";
	if(!this.variations[this.currentVariation].backs.length) {
		this.frontBack = "front";
		this.$elmts._menu._buttons.view.addClass("disabled");
	} else {
		this.$elmts._menu._buttons.view.removeClass("disabled");
	}
	this.$elmts._menu._buttons.view.find("span.detailMenuLabel").text(this.frontBack == "back" ? string_VIEW_FRONT : string_VIEW_BACK);
	
	return this;
};
WatchDetail.prototype.setZoomLevel = function(z) {
	if(typeof z == "number") {
		if(z <= 0) {
			this.currentZoomLevel = 0;
		} else if(z >= this.variations[this.currentVariation][this.frontBack+"s"].length-1) {
			this.currentZoomLevel = this.variations[this.currentVariation][this.frontBack+"s"].length-1;
		} else {
			this.currentZoomLevel = z;
		}
	}
	
	if(this.currentZoomLevel <= 0) {
		this.$elmts._menu._buttons.zoomIn.addClass("disabled");
	} else {
		this.$elmts._menu._buttons.zoomIn.removeClass("disabled");
	}
	if(this.currentZoomLevel >= this.variations[this.currentVariation][this.frontBack+"s"].length-1) {
		this.$elmts._menu._buttons.zoomOut.addClass("disabled");
	} else {
		this.$elmts._menu._buttons.zoomOut.removeClass("disabled");
	}
	
	return this;
};
WatchDetail.prototype._selectImage = function(index, state, zoom) {
	var surrogate = this;
	
	this.setVariation(index).setFrontBack(state).setZoomLevel(zoom);
		
	this.$elmts.imageContainer.empty();
	// Show spinner
	this.$elmts.spinner.clearQueue().hide().fadeIn(500);
	
	// Load large image
	var imgSrc = surrogate.variations[surrogate.currentVariation][surrogate.frontBack+"s"][surrogate.currentZoomLevel];
	$.loadImages(imgSrc, function() {
		surrogate.$elmts.image = $("<img/>", {
			"class" : "largeImage",
			"src" : imgSrc,
			"alt" : ""
		}).appendTo(surrogate.$elmts.imageContainer.empty());
		var span = $("<span/>", {"class":"largeImage"}).css({
			backgroundImage : "url('"+imgSrc+"')",
			left : (($(window).width() - surrogate.$elmts.image.width())/2),
			top : (($(window).height() - surrogate.$elmts.image.height())/2)
		}).width(surrogate.$elmts.image.width()).height(surrogate.$elmts.image.height());
		surrogate.$elmts.image.replaceWith(span);
		surrogate.$elmts.image = span;
		surrogate.$elmts.spinner.show().delay(250).fadeOut(500);
		window.location.hash = surrogate.getCurrentHash();
	});
};
WatchDetail.prototype._updateWindow = function() {
	var surrogate = this;
	
	this.$elmts.watchDetail.width($(window).width()-20).height($(window).height()-20);
	this.$elmts.imageContainer.trigger("mousedown").trigger("mouseup");
	
	var htDiff = this.$elmts.window.height() - this.$elmts._menu.container.height();
	if(htDiff > 0) {
		if(this.menuScrollable) {
			this.menuScrollable = false;
		}
		this.$elmts._menu.container.css({"top" : htDiff/2});
	} else {
		if(!this.menuScrollable) {
			this.menuScrollable = true;
		this.$elmts._menu.container.css({"top" : 0});
		}
	}
};
WatchDetail.prototype._menuScroll = function(delta) {
};
WatchDetail.prototype._buildMenuElmts = function() {
	var surrogate = this;
	
	this.$elmts._menu = {};
	this.$elmts._menu.container = $("<div/>", {"class":"detailMenu hidden"}).css({"right":-202}).hoverIntent({
		over : function() {
				$(this).animate({"right":0}, {
					duration : 200,
					easing : "easeOutQuad",
					complete : function() {
						$(this).removeClass("hidden");
					}
				});
			},
		out : function() {
				$(this).animate({"right":-202}, {
					duration : 200,
					easing : "easeOutQuad",
					complete : function() {
						$(this).addClass("hidden");
					}
				});
			},
		timeout : 750
	}).appendTo(this.$elmts.window);
	
	this.$elmts._menu.panel1 = $("<div/>", {"class":"detailMenuPanel"}).appendTo(this.$elmts._menu.container);
	this.$elmts._menu.panel2 = $("<div/>", {"class":"detailMenuPanel"}).appendTo(this.$elmts._menu.container);
	this.$elmts._menu.panel3 = $("<div/>", {"class":"detailMenuPanel detailMenuThumbnailPanel"}).append($("<span/>", {"class":"icon"})).appendTo(this.$elmts._menu.container);
	this.$elmts._menu.thumbnailContainer = $("<ul/>", {"class":"detailMenuThumbnails"}).appendTo(this.$elmts._menu.panel3);
	this.$elmts._menu._buttons = {};
	this.$elmts._menu._thumbnails = [];
	
	// Image Operations Panel (panel1)
	this.$elmts._menu._buttons.close = $("<div/>", {
		"class" : "detailMenuButton detailButtonClose",
		"click" : function() {
				surrogate.close();
			}
	}).append(
		$("<span/>", {"class":"icon"})
	).append(
		$("<span/>", {"class":"detailMenuLabel","html": string_CLOSE_RETURN})
	).appendTo(this.$elmts._menu.panel1);
	
	this.$elmts._menu._buttons.zoomIn = $("<div/>", {
		"class" : "detailMenuButton detailButtonZoomIn",
		"click" : function() {
			if(!$(this).hasClass("disabled")) {
				surrogate._selectImage(surrogate.currentVariation, surrogate.frontBack, surrogate.currentZoomLevel-1);
			}
		}
	}).append(
		$("<span/>", {"class":"icon"})
	).append(
		$("<span/>", {"class":"detailMenuLabel","text":string_ZOOM_IN})
	).appendTo(this.$elmts._menu.panel1);
	
	this.$elmts._menu._buttons.zoomOut = $("<div/>", {
		"class" : "detailMenuButton detailButtonZoomOut",
		"click" : function() {
			if(!$(this).hasClass("disabled")) {
				surrogate._selectImage(surrogate.currentVariation, surrogate.frontBack, surrogate.currentZoomLevel+1);
			}
		}
	}).append(
		$("<span/>", {"class":"icon"})
	).append(
		$("<span/>", {"class":"detailMenuLabel","text":string_ZOOM_OUT})
	).appendTo(this.$elmts._menu.panel1);
	
	this.$elmts._menu._buttons.view = $("<div/>", {
		"class" : "detailMenuButton detailButtonView",
		"click" : function() {
			if(!$(this).hasClass("disabled")) {
				surrogate._selectImage(surrogate.currentVariation, surrogate.frontBack == "back" ? "front" : "back", surrogate.currentZoomLevel);
			}
		}
	}).append(
		$("<span/>", {"class":"icon"})
	).append(
		$("<span/>", {"class":"detailMenuLabel","text":"View Watch Back"})
	).appendTo(this.$elmts._menu.panel1);
	
	// External Operations Panel (panel2)
	this.$elmts._menu._buttons.share = $("<div/>", {
		"class" : "detailMenuButton detailButtonShare"
	}).append(
		$("<span/>", {"class":"icon"})
	).append(
		$("<span/>", {
			"class" : "detailMenuLabel shareBar",
			"text" : string_SHARE + ":"
		}).append( //Twitter
			$("<a/>", {
				"class" : "twitter",
				"href" : "http://twitter.com/share?url="+(window.location.toString())+"&amp;text="+$("title").text()
			}).append(
				$("<span/>", {"class":"icon"})
			)
		).append( // Facebook
			$("<a/>", {
				"class" : "facebook",
				"href" : "#facebook"
			}).append(
				$("<span/>", {"class":"icon"})
			)
		).append( // Email
			$("<a/>", {
				"class" : "email",
				"href" : "#email"
			}).append(
				$("<span/>", {"class":"icon"})
			)
		).append( // Facebook tooltip stuff
			$("<div>", {"class":"fbLinks"}).append(
				$("<ul/>").append(
					$("<li/>", {
						"class" : "fb_like",
						"html" : '<iframe src="http://www.facebook.com/plugins/like.php?href='+window.location.toString()+'&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px; height:21px;" allowTransparency="true"></iframe>'
					})
				).append(
					$("<li/>", {"class" : "fb_share"}).append(
						$("<a/>", {
							"name" : "fb_share",
							"type" : "button",
							"href" : "http://www.facebook.com/sharer.php?u="+window.location.toString(),
							"html" : "<span class='FBConnectButton FBConnectButton_Small' style='cursor:pointer;'><span class='FBConnectButton_Text'>Share</span></span>"
						}).attr("share_url", window.location.toString())
					)
				)
			)
		)
	).appendTo(this.$elmts._menu.panel2).shareBarInit();
	
	this.$elmts._menu._buttons.download = $("<div/>", {
		"class" : "detailMenuButton detailButtonDownload",
		"click" : function() { window.open(surrogate.variations[surrogate.currentVariation][surrogate.frontBack+"s"][0]) }
	}).append(
		$("<span/>", {"class":"icon"})
	).append(
		$("<span/>", {"class":"detailMenuLabel","text":string_DOWNLOAD_HI_RES})
	).appendTo(this.$elmts._menu.panel2);
	
	/*this.$elmts._menu._buttons.send = $("<div/>", {
		"class" : "detailMenuButton detailButtonSend",
		"click" : function() {}
	}).append(
		$("<span/>", {"class":"icon"})
	).append(
		$("<span/>", {"class":"detailMenuLabel","text":"Send To A Friend"})
	).appendTo(this.$elmts._menu.panel2);*/
	
	$(".detailMenuButton", this.$elmts._menu.container).bind("click", function() {
		surrogate.$elmts._menu.container.stop(true);
	});
	
	// Variations Panel (panel3)
	for(var z=0; z<this.variations.length; z++) {
		this.$elmts._menu._thumbnails.push(
			$("<li/>", {
				"class" : "detailMenuThumbnail",
				"click" : function() {
						if(!$(this).hasClass("selected")) {
							var myIndex = surrogate.$elmts._menu.panel3.find("li").index($(this));
							surrogate._selectImage(myIndex, "front", surrogate.currentZoomLevel);
						}
					}
			}).prepend(
				$("<img/>", {
					"src" : this.variations[z].thumbnail,
					"alt" : this.variations[z].title
				})
			).appendTo(this.$elmts._menu.thumbnailContainer)
		);
	}
};
WatchDetail.prototype._hashCheck = function() {
	var hash = window.location.hash.substr(1).split("/");
	if(hash[0] == "enlarge") {
		var returnObj = {};
		for(var p=1; p<hash.length; p++) {
			if(hash[1].split("-").length>1 && hash[p].split("-")[0] == "variation") {
				returnObj.variation = parseInt(hash[p].split("-")[1])-1;
			} else if(hash[1].split("-").length>1 && hash[p].split("-")[0] == "zoom") {
				returnObj.zoomLevel = parseInt(hash[p].split("-")[1])-1;
			} else if(hash[p] == "front" || hash[p] == "back") {
				returnObj.frontBack = hash[p];
			}
		}
		
		returnObj.variation = typeof returnObj.variation == "number" ? returnObj.variation : 0;
		returnObj.zoomLevel = typeof returnObj.zoomLevel == "number" ? returnObj.zoomLevel : 0;
		returnObj.frontBack = (returnObj.frontBack == "front" || returnObj.frontBack == "back") ? returnObj.frontBack : "front";
		return returnObj;
	} else {
		return false;
	}
};
WatchDetail.prototype.getCurrentHash = function() {
	return "#enlarge/variation-"+(this.currentVariation+1)+"/"+this.frontBack+"/zoom-"+(this.currentZoomLevel+1);
}

$.fn.extend({
	buildWatchDetail : function($enlargeButtons) {
		var surrogate = this;
		var variationsData = [];
		
		$(this).eq(0).find(".variation").each(function() {
			variationsData.push({
				thumbnail : $("img.thumbnail", this).attr("src"),
				fronts : $("a", this).data("front") ? $("a", this).data("front").split(",") : [],
				backs : $("a", this).data("back") ? $("a", this).data("back").split(",") : [],
				title : $("a", this).attr("title") != "" ? $("a", this).attr("title") : false
			});
		});
		
		if(variationsData.length) {
			var watchDetailObj = new WatchDetail(variationsData);
			$(this).eq(0).data("watchDetail", watchDetailObj);
			
			$(this).eq(0).find("li").each(function(index) {
				$(this).bind("click", function(e) {
					e.preventDefault();
					watchDetailObj.setVariation(index);
					$enlargeButtons.filter("a").attr("href", watchDetailObj.getCurrentHash());
				});
			});
			
			/*for(t=0; t<watchDetailObj.$elmts._menu._thumbnails.length; t++) {
				watchDetailObj.$elmts._menu._thumbnails[t].bind("click", function() {
					$(surrogate).eq(0).find(".variation").eq(t).trigger("click");
				}); 
			}*/
			
			$enlargeButtons.bind("click", function(event) {
				event.preventDefault();
				watchDetailObj.open();
			});
			
			return watchDetailObj;
		} else {
			return false;
		}
	}
});


// Keyboard inputs!
var G_KEYCODES = {backspace:8,tab:9,enter:13,"shift":16,ctrl:17,alt:18,capsLock:20,esc:27,pageUp:33,pageDown:34,end:35,"home":36,left:37,up:38,right:39,down:40,insert:45,"delete":46,"0":48,"1":49,"2":50,"3":51,"4":52,"5":53,"6":54,"7":55,"8":56,"9":57,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,leftWindows:91,rightWindows:92,numpad0:96,numpad1:97,numpad2:98,numpad3:99,numpad4:100,numpad5:101,numpad6:102,numpad7:103,numpad8:104,numpad9:105,multiply:106,add:107,subtract:109,decimalPoint:110,divide:111,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,numLock:144,scrollLock:145,semicolon:186,equalSign:187,comma:188,dash:189,period:190,slash:191,grave:192,bracketOpen:219,backslash:220,bracketClose:221,singleQuote:222};


// --- SERVICE INTERVENTIONS ---
$(function() {
	$("#interventions").each(function(){
		$(this).setupInterventions();
	});
});

$.fn.extend({
	setupInterventions : function() {
		var surrogate = this;
		$("<ul/>", {"class":"interventionTabs"}).appendTo($(this).find(".header"));
		$(this).find(".intervention").each(function() {
			var tab = $("<li/>", {"class":"interventionTab"}).html($(this).find(".title").html()).data("myContent", $(this));
			tab.appendTo($(surrogate).find(".interventionTabs"))
			$(this).data("myTab", tab);
			$(this).find(".title").remove();
			$(this).data("InterventionSteps", (new InterventionSteps($(this).find(".steps"))));
			$(this).data("myTab").bind("click", function() {
				if(!$(this).hasClass("selected")) {
					$(surrogate).find(".interventionTab.selected").removeClass("selected");
					$(this).addClass("selected");
					$(surrogate).find(".intervention:not(.hidden)").addClass("hidden");
					$(this).data("myContent").removeClass("hidden");
					$(surrogate).find(".interventionTabs .indicator").animate({
						left : (($(this).outerWidth()-$(surrogate).find(".interventionTabs .indicator").width())/2)+$(this).position().left
					}, 500, GLOBAL_EASING);
				}
			});
		});
		$(this).find(".intervention:gt(0)").addClass("hidden");
		$(this).find(".interventionTab:eq(0)").addClass("selected");
		
		var indicator = $("<div/>", {"class":"indicator"}).appendTo($(this).find(".interventionTabs"));
		var indicatorWd = $(this).find(".indicator").width();
		var tabWd = $(this).find(".interventionTab:not(.hidden)").outerWidth();
		var tabLeft = $(this).find(".interventionTab.selected").position().left;
		indicator.css({left:((tabWd-indicatorWd)/2)+tabLeft});
	}
});

var InterventionSteps = function($steps) {
	var surrogate = this;
	$steps = $steps.eq(0);
	
	this.currentStep = 0;
	this.isAnimating = false;
	
	this.$elmts = {};
	this.$elmts.container = $steps;
	this.$elmts._steps = $steps.find(".step");
	this.$elmts.tray = $steps.wrapInner($("<div/>", {"class":"stepsTray"}).width($steps.find(".step").length*$steps.find(".step").eq(1).outerWidth())).find(".stepsTray");
	this.$elmts.window = $steps.wrapInner($("<div/>", {"class":"stepsWindow"})).find(".stepsWindow");
	
	this.$elmts._nav = {};
	this.$elmts._nav.container = $("<ol/>", {"class":"stepsNav"}).width(this.$elmts._steps.length*28).appendTo(this.$elmts.container);
	
	var largestHt = 0;
	var paddingDif = this.$elmts._steps.eq(0).outerHeight(false) - this.$elmts._steps.eq(0).height();
	for(var s=0; s < this.$elmts._steps.length; s++) {
		$("<h5/>", {
			"class":"number",
			"text":(s+1).toStringOfLength(2)
		}).insertAfter(this.$elmts._steps.eq(s).find("img"));
		$("<li/>", {
			"text" :(s+1).toStringOfLength(2),
			"click" : function() { surrogate.turnToStep($(this).data("myIndex")); }
		}).data("myIndex", s).appendTo(this.$elmts._nav.container);
		var thisHt = this.$elmts._steps.eq(s).height();
		largestHt = thisHt > largestHt ? thisHt : largestHt;
	}
	this.$elmts._steps.height(largestHt);
	this.$elmts.window.height(largestHt+paddingDif);
	
	this.$elmts._nav._numbers = this.$elmts._nav.container.find("li");
	this.$elmts._nav.indicator = $("<div/>", {"class":"indicator"}).appendTo(this.$elmts._nav.container);
	this.$elmts._nav.buttons = $("<div/>", {"class":"stepsNavButtons"}).appendTo(this.$elmts._nav.container);
	this.$elmts._nav.prevButton = $("<span/>", {
		"class" : "prev",
		"click" : function() { surrogate.turnToStep(surrogate.currentStep-4); }
	}).appendTo(this.$elmts._nav.buttons);
	this.$elmts._nav.nextButton = $("<span/>", {
		"class" : "next",
		"click" : function() { surrogate.turnToStep(surrogate.currentStep+4); }
	}).appendTo(this.$elmts._nav.buttons);
	
	this.$elmts._nav.indicator.add(this.$elmts._nav.buttons).css({left:this.currentStep*243});
	
	if(this.currentStep <= 0) {
		this.$elmts._nav.prevButton.addClass("disabled").fadeOut(500, GLOBAL_EASING);
	} else {
		this.$elmts._nav.prevButton.removeClass("disabled").fadeIn(500, GLOBAL_EASING);
	}
	
	if(this.currentStep >= this.$elmts._steps.length-4) {
		this.$elmts._nav.nextButton.addClass("disabled").fadeOut(500, GLOBAL_EASING);
	} else {
		this.$elmts._nav.nextButton.removeClass("disabled").fadeIn(500, GLOBAL_EASING);
	}
};
InterventionSteps.prototype.turnToStep = function(index) {
	var surrogate = this;
	if(!this.isAnimating) {
		if(index < 0) {
			index = 0;
		} else if(index > this.$elmts._steps.length-4) {
			index = this.$elmts._steps.length-4;
		}
		
		if(index !== this.currentStep) {
			this.currentStep = index;
			this.isAnimating = true;
			var navLeft = this.$elmts._nav._numbers.eq(index).position().left;
			var trayLeft = index*-243;
			this.$elmts.tray.animate({left:trayLeft}, {duration:500,easing:GLOBAL_EASING});
			this.$elmts._nav.indicator.add(this.$elmts._nav.buttons).animate({left:navLeft},{
				duration : 500,
				easing : GLOBAL_EASING,
				complete : function() {
						surrogate.isAnimating = false;
						if(surrogate.currentStep <= 0) {
							surrogate.$elmts._nav.prevButton.addClass("disabled").fadeOut(200);
						}
						
						if(surrogate.currentStep >= surrogate.$elmts._steps.length-4) {
							surrogate.$elmts._nav.nextButton.addClass("disabled").fadeOut(200);
						}
					}
			});
			
			if(surrogate.currentStep > 0){
				surrogate.$elmts._nav.prevButton.removeClass("disabled").fadeIn(200);
			}
			if(surrogate.currentStep < surrogate.$elmts._steps.length-4) {
				surrogate.$elmts._nav.nextButton.removeClass("disabled").fadeIn(200);
			}
		}
	}
	return this;
};

Number.prototype.toStringOfLength = function(len,pad) {
	var str = this.toString();
	pad = typeof pad == "string" ? pad : "0";
	while(str.length < len){
		str = pad + str;
	}
	return str;
}

// --- IWC LIGHTBOX SLIDESHOW ---
$(function() {
	$("ul.lightbox").iwcLightbox();
});

function IWCLightBox(imageArray, options) {
	var surrogate = this;
	
	var defaults = {
		isOpen : false,
		currentImage : 0,
		verticalBuffer : 100,
		animate : true
	};
	$.extend(true, this, defaults, options);
	
	this.images = imageArray;
	this.isLoading = false;
	this.$elmts = {};
	
	// Build Elements
	this.$elmts.lightBox = $("<div/>", {"class":"lightBox"}).css({
		"position" : "fixed",
		"top" : 0,
		"left" : 0,
		"width" : "100%",
		"height" : "100%",
		"zIndex" : 500
	}).data("lightBox", this);
	if(opacitySupport) {
		this.$elmts.lightBox.css({"opacity":0});
	}
	
	this.$elmts.overlay = $("<div/>", {"class":"overlay"}).css({
		"position" : "absolute",
		"top" : 0,
		"left" : 0,
		"width" : "100%",
		"height" : "100%"
	}).appendTo(this.$elmts.lightBox);
	
	this.$elmts.container = $("<div/>", {"class":"container"}).css({
		"position" : "absolute"
	}).appendTo(this.$elmts.lightBox);
	
	this.$elmts.controls = $("<div/>", {"class":"controls"}).appendTo(this.$elmts.container);
	
	this.$elmts.prevButton = $("<span/>", {
		"class" : "prevButton",
		"click" : function() {
				if(!$(this).hasClass("disabled")) {
					surrogate.goToImage(surrogate.currentImage-1, this.animate);
				}
			}
	}).appendTo(this.$elmts.controls);
	
	this.$elmts.firstButton = $("<span/>", {
		"class" : "firstButton",
		"click" : function() {
				if(!$(this).hasClass("disabled")) {
					surrogate.goToImage(0, this.animate);
				}
			}
	}).appendTo(this.$elmts.controls);
	
	this.$elmts.closeButton = $("<span/>", {
		"class" : "closeButton",
		"click" : function() {
				surrogate.close();
			}
	}).appendTo(this.$elmts.controls);
	
	this.$elmts.nextButton = $("<span/>", {
		"class" : "nextButton",
		"click" : function() {
				if(!$(this).hasClass("disabled")) {
					surrogate.goToImage(surrogate.currentImage+1, this.animate);
				}
			}
	}).appendTo(this.$elmts.controls);
	
	this.$elmts.imageContainer = $("<div/>", {"class":"imageContainer"}).css({
		"position" : "relative",
		"min-height" : 100,
		"text-align" : "center"
	}).appendTo(this.$elmts.container);
	
	this.$elmts.spinner = $("<div/>", {"class":"spinner"}).css({
		"display" : "none",
		"position" : "absolute",
		"top" : "50%",
		"left" : "50%"
	}).append($("<span/>")).appendTo(this.$elmts.imageContainer);
	
	this.$elmts.image = null;
	
	var hashVal = this._hashCheck();
	if(hashVal !== false) {
		this.setImage(hashVal);
		this.open();
	} else if(this.isOpen) {
		this.open();
	}
};
IWCLightBox.prototype.open = function() {
	var surrogate = this;
	this.isOpen = true;
	
	this.$elmts.lightBox.appendTo("body");
	surrogate.goToImage(surrogate.currentImage, false);
	
	$(window).bind("resize.lightBox", function() { surrogate._updatePosition(); });
	this._updatePosition();
	
	if(opacitySupport) {
		this.$elmts.lightBox.fadeTo(300, 1);
	} else {
		this.$elmts.lightBox.show();
	}
	
	$(document).bind("keyup.lightBox", function(e) {
		switch (typeof e.keyCode == "number" ? e.keyCode : e.which) {
			case G_KEYCODES.esc :
				surrogate.close();
				break;
			case G_KEYCODES.left :
				surrogate.$elmts.prevButton.trigger("click");
				break;
			case G_KEYCODES.right :
				surrogate.$elmts.nextButton.trigger("click");
				break;
		}
	});
	
	return this;
};
IWCLightBox.prototype.close = function() {
	if(this.isOpen) {
		var surrogate = this;
		
		$(document).unbind("keyup.lightBox");
		
		var top = this.$elmts.overlay.offset().top;
		window.location.hash = "";
		if($.scrollTo) { $.scrollTo(top); }
		
		if(opacitySupport) {
			this.$elmts.lightBox.fadeTo(300, 0, function() {
				surrogate.$elmts.lightBox.detach();
				
				$(window).unbind("resize.lightBox");
				surrogate.isOpen = false;
			});
		} else {
			this.$elmts.lightBox.hide().detach();
			$(window).unbind("resize.lightBox");
			this.isOpen = false;
		}
	}
	return this;
};
IWCLightBox.prototype.setImage = function(index) {
	if(typeof index != "number") {
		index = parseInt(index);
	}
	if(index < 0) {
		index = 0;
	} else if(index >= this.images.length) {
		index = this.images.length-1;
	}
	
	this.currentImage = index;
	
	if(this.currentImage <= 0) {
		this.$elmts.prevButton.addClass("disabled");
		this.$elmts.firstButton.addClass("disabled");
	} else {
		this.$elmts.prevButton.removeClass("disabled");
		this.$elmts.firstButton.removeClass("disabled");
	}
	
	if(this.currentImage >= this.images.length-1) {
		this.$elmts.nextButton.addClass("disabled");
	} else {
		this.$elmts.nextButton.removeClass("disabled");
	}
	
	return this;
};
IWCLightBox.prototype.goToImage = function(index, anim) {
	if(!this.isLoading) {
		var surrogate = this;
		anim = typeof anim == "boolean" ? anim : true;
		anim = this.isOpen && this.animate ? anim : false;
		
		this.setImage(index);
		
		// Spinner
		this.$elmts.spinner.clearQueue().hide().fadeIn(200);
		this.isLoading = true;
		
		$.loadImages(this.images[index], function() {
			var oldImage = surrogate.$elmts.image;
			surrogate.$elmts.image = $("<img/>", {
				"src" : surrogate.images[index],
				"alt" : ""
			}).css({"opacity":0});
			surrogate.$elmts.spinner.show().delay(10).fadeOut(200);
			if(anim && oldImage) {
				oldImage.fadeOut(300, function() {
					oldImage.remove();
					surrogate.$elmts.image.appendTo(surrogate.$elmts.imageContainer);
					surrogate._updatePosition();
					surrogate.$elmts.image.fadeTo(300, 1, function() {
						window.location.hash = surrogate.getCurrentHash();
						surrogate.isLoading = false;
					});
				});
			} else {
				if(oldImage) { oldImage.remove(); }
				surrogate.$elmts.image.appendTo(surrogate.$elmts.imageContainer).fadeTo(0,1);
				surrogate._updatePosition();
				window.location.hash = surrogate.getCurrentHash();
				surrogate.isLoading = false;
			}
		});
	}
};
IWCLightBox.prototype._updatePosition = function() {
	var surrogate = this;
	var htDiff = $(window).height() - this.$elmts.container.outerHeight(false);
	if(htDiff > 0) {
		if(this.scrollable) {
			this.scrollable = false;
			$(window).unbind("scroll.lightbox");
		}
		if(htDiff > this.verticalBuffer*2) {
			this.$elmts.container.css({"top":this.verticalBuffer});
		} else {
			this.$elmts.container.css({"top":htDiff/2});
		}
	} else {
		if(!this.scrollable) {
			this.scrollable = true;
			this.overlayTop = this.$elmts.overlay.offset().top;
			$(window).bind("scroll.lightbox", function() {
				var topDiff = surrogate.overlayTop - surrogate.$elmts.overlay.offset().top;
				surrogate.overlayTop = surrogate.$elmts.overlay.offset().top;
				surrogate._scroll(topDiff);
			});
		}
	}
	this.$elmts.container.css({"left":($(window).width()-this.$elmts.container.outerWidth(false))/2});
};
IWCLightBox.prototype._scroll = function(delta) {
	var diff = $(window).height() - this.$elmts.container.outerHeight();
	var newTop =  this.$elmts.container.position().top + delta;
	if(newTop > 0) {
		newTop = 0;
	} else if(newTop < diff) {
		newTop = diff;
	}
	this.$elmts.container.css({"top" : newTop});
};
IWCLightBox.prototype._hashCheck = function() {
	var hash = window.location.hash.substr(1).split("/");
	if(hash[0] == "slideshow") {
		return hash.length>1 ? parseInt(hash[1])-1 : 0;
	} else {
		return false;
	}
};
IWCLightBox.prototype.getCurrentHash = function() {
	return "#slideshow/"+(this.currentImage+1);
}


$.fn.iwcLightbox = function() {
	$(this).each(function() {
		var surrogate = $(this), imageArray = [], lightBox, firstLI = $(this).find("li").eq(0), boxHt, boxWd, launcher;
			
		surrogate.find("li:gt(0)").each(function() {
			imageArray.push($(this).find("img").attr("src"));
			$(this).detach();
		});
		
		firstLI.find("img").bind("load", function() {
			boxHt = firstLI.find("img").height();
			boxWd = firstLI.find("img").width();
			
			firstLI.detach();
			
			lightBox = new IWCLightBox(imageArray);
			
			launcher = $("<div/>", {
				"class" : "lightBoxLauncher "+surrogate.attr("class").replace(/lightbox/g, ""),
				"html" : firstLI.html(),
				"click" : function() {
					lightBox.open()
				}
			}).height(boxHt).width(boxWd);
			
			launcher.find("img").prependTo(launcher);
			launcher.find("h4, p").wrapAll("<div class='titles'/>");
			launcher.append($("<div/>", {"class":"launchButton"}));
			
			surrogate.replaceWith(launcher);
		
		});
		
		if(firstLI.find("img").get(0).complete){
			firstLI.find("img").trigger("load");
		}
	});
};

// --- FAQ PAGE ---
$(function() {
	$(".faq table tbody tr:not(:first-child) .category *").hide();
	$(".faq table .answer div").each(function() {
		var surrogate = this;
		var tallHt = $(this).height();
		var clone = $(this).clone().addClass("clone").css({overflow:"hidden"}).height($(surrogate).height());
		if($(this).truncateBlockAtHeight(108, " ...")) {
			var shortHt = $(this).height();
			$("<span/>", {
				"class" : "expand",
				"text" : string_EXPAND_FOR_ANSWER,
				"click" : function() {
						if($(this).parent().hasClass("expanded")) {
							// Contract
							$(this).text(string_EXPAND_FOR_ANSWER).parent().removeClass("expanded");
							clone.animate({height:shortHt}, 300, GLOBAL_EASING, function() {
								$(this).replaceWith($(surrogate));
							});
						} else {
							// Expand
							$(surrogate).replaceWith(clone);
							clone.height(shortHt).animate({height:tallHt}, 300, GLOBAL_EASING);
							$(this).text(string_COLLAPSE_ANSWER).parent().addClass("expanded");
						}
					}
			}).insertAfter($(this));
		}
	});
});

// --- IWC VIDEO ---
$(function() {
	$(".iwcVideo").buildVideoPlayer();
	
	// I'm not proud of this.
	if(navigator.userAgent.match(/Android/i)) {
		$(".iwcVideo").each(function() {
			var expID = "bc_"+$(this).attr("id").split("-")[1];
			setTimeout(function() { onTemplateLoaded(expID, true); }, 2000);
		});
	}
});

function onTemplateLoaded(experienceID, bypass) {
	if(bypass || ("iPad iPhone iPod").indexOf(navigator.platform) > -1) {
		$("#video-"+experienceID.replace('bc_','')).data("videoController").open();
	} else {
		$("#video-"+experienceID.replace('bc_','')).data("videoController").initBrightcoveAPI(experienceID);
	}
}



$.fn.buildVideoPlayer = function() {
	$(this).each(function() {
		if(!$(this).data("videoController")) {
			if($(this).hasClass("videoFull")) {
				var iwcVP = new IWCVideoPlayer($(this), "full");
			} else if($(this).hasClass("videoTwoThirds")) {
				var iwcVP = new IWCVideoPlayer($(this), "twothirds");
			}
		}
	});
}

var IWCVideoPlayer = function($container, aType) {
	var surrogate = this;
	
	this.type = aType == "full" ? "full" : "twothirds";
	this.bcLoaded = false;
	this.bc = null;
	this.isPlaying = false;
	
	this.$elmts = {};
	
	this.$elmts.container = $container.data("videoController", this);
	
	this.$elmts.poster = $container.find(".poster");
	this.$elmts.video = $container.find(".bcVideo");
	
	this.$elmts.overlay = $("<div/>", {
		"class" : "videoFadeOverlay"
	}).css({
		"display" : "none",
		"position" : "absolute",
		"top" : 0,
		"left" : 0,
		"width" : "100%",
		"height" : "100%",
		"zIndex" : 4
	});
	
	$(window).bind("resize.videoPlayer", function() {
		surrogate.$elmts.overlay.width($(document).width()).height($(document).height());
	});
	$(window).trigger("resize.videoPlayer");
	
	this.$elmts.playButton = $("<div/>", {
		"class" : "playButton",
		"click" : function() {
			surrogate.open();
		}
	});
	
	this.$elmts.closeButton = $("<div/>", {
		"class" : "videoCloseButton",
		"text" : this.type == "twothirds" ? "Close" : "",
		"click" : function() {
			surrogate.close();
		}
	});
	
	//var scrpt = $('<script/>',{"src":"http://admin.brightcove.com/js/BrightcoveExperiences_all.js"}).appendTo(this.$elmts.video);
};
IWCVideoPlayer.prototype.open = function() {
	var surrogate = this;
	this.play();
	this.$elmts.video.css({"left":0});
	this.$elmts.poster.delay(50).fadeOut(400, function() {
		if(surrogate.type == "full") {
			surrogate.$elmts.container.delay(100).animate({height : surrogate.$elmts.video.height()}, 400, function(){
				surrogate.$elmts.container.css({"zIndex":5});
				if(surrogate.bc) {
					surrogate.$elmts.overlay.appendTo("body");
					$(window).trigger("resize.videoPlayer");
					surrogate.$elmts.overlay.fadeIn(400);
					surrogate.$elmts.closeButton.appendTo("body").css({
						top : surrogate.$elmts.video.offset().top,
						left : surrogate.$elmts.video.offset().left + surrogate.$elmts.video.width()
					}).hide().fadeIn(200);
				}
			});
		} else if(surrogate.type =="twothirds") {
			if(surrogate.bc) {
				surrogate.$elmts.closeButton.appendTo(surrogate.$elmts.container).hide().fadeIn(200);
			}
		}
	});
};
IWCVideoPlayer.prototype.close = function() {
	if(this.bc) {
		var surrogate = this;
		
		this.$elmts.closeButton.fadeOut(200, function() { $(this).detach(); });
		
		this.$elmts.poster.fadeIn(400, function() {
			surrogate.pause();
			surrogate.$elmts.video.css({"left":4000});
			if(surrogate.type == "full") {
				surrogate.$elmts.container.delay(100).animate({height : surrogate.$elmts.poster.height()}, 400, function(){
					surrogate.$elmts.overlay.fadeOut(400, function() {
						$(this).detach();
						surrogate.$elmts.container.css({"zIndex":"auto"});
					});
				});
			}
		});
	}
};
IWCVideoPlayer.prototype.play = function() {
	if(this.bc && !this.isPlaying) {
		this.bc._modules.videoPlayer.play();
		this.isPlaying = true;
	}
};
IWCVideoPlayer.prototype.pause = function() {
	if(this.bc && this.isPlaying) {
		this.bc._modules.videoPlayer.pause();
		this.isPlaying = false;
	}
};
IWCVideoPlayer.prototype._activate = function() {
	if(!this.bcLoaded) {
		this.$elmts.playButton.appendTo(this.$elmts.poster).hide().fadeIn(200);
		this.bcLoaded = true;
	}
};
IWCVideoPlayer.prototype.initBrightcoveAPI  = function(experienceID) {
	var surrogate = this, vp, ex, co;
	
	if(!this.bc) {
		this.bc = {
			expID : experienceID,
			exp : brightcove.getExperience(experienceID)
		};
		
		vp = this.bc.exp.getModule(APIModules.VIDEO_PLAYER);
		ex = this.bc.exp.getModule(APIModules.EXPERIENCE);
		co = this.bc.exp.getModule(APIModules.CONTENT);
		
		if(vp && ex && co) {
			this.bc._modules = {
				videoPlayer : vp,
				experience : ex,
				content : co
			};
			
			this.bc._modules.videoPlayer.addEventListener(BCMediaEvent.COMPLETE, function() {});
			this.bc._modules.experience.addEventListener(BCExperienceEvent.CONTENT_LOAD, function() {
				surrogate._activate();
			});
			
			this.bc._modules.content.addEventListener(BCContentEvent.VIDEO_LOAD, function() {
				surrogate._activate();
			});
		} else {
			this.bc = false;
			this.open();
		}
	}
};

