/*
* 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.category == "MCBE")){
						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'));
	});

	$('a[href^="' + url_MCBE_ENTRY + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});

    $('a[href^="' + url_MCBE_ENTRY_HONGKONG + '"]').live('click', function(e){
   		e.preventDefault();
   		getForm($(this).attr('href'));
   	});

	$('a[href^="' + url_SIDERALE_CONTACT + '"]').live('click', function(e){
		e.preventDefault();
		getForm($(this).attr('href'));
	});

	// FIX FOR MULTIPLE SUBMIT CLICKS IN CERTAIN FORMS
	var submitButtonList = $("form input[type=submit]");
	submitButtonList.bind("click", function(e){
		var tempItem = $(this);
		tempItem.fadeTo(0, .5).addClass('disabled');
		setTimeout(function(){
			tempItem.attr('disabled', 'disabled');
		}, 100);
	});
}

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 });

		Custom.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 currURL = undefined;
	var query = String(window.location).split("?")[1];

	if(query != undefined && query != null && query != ""){
	    if(query.indexOf("&filter=") >= 0){
	        currURL = query.split("&")[1].split("=")[1];
	    }
	    else if(query.indexOf("type=") >= 0){
	        currURL = query.split("=")[1];
	    }
	}

	// console.log("currURL : " + currURL);

	if(currURL === undefined || currURL === null || currURL === "" || currURL === "all"){
	    as.each(function(){
	       var asID = String($(this).attr("id"));
	       // console.log("asID : "+asID);
           // console.log("currURL : "+currURL);
	       if(asID === undefined || asID === null || asID === ""){
                $(this).addClass('selected');
           }
	    });
	}
	else{
	    as.each(function(){
           var asID = String($(this).attr("id"));
           // console.log("asID : "+asID);
           // console.log("currURL : "+currURL);
           if(currURL === asID){
                $(this).addClass('selected');
           }
        });
	}

	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(e){
		var t = $(this);
		var cat = t.attr('href')//.substring(1);
		// console.log("cat : " + cat );
		// 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');
		window.location.href = cat;
		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
				// this.unbind('submit');//WHOOPS! endless loop
				console.log("Submit Clicked Modal Contact Window!");
				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;
	var handleColor = options.handleColor;
	if($('body').hasClass('siderale')){
		handleColor = "#8b8b89";
	}


	indicator.css({position:'absolute', top:0, left:0, height:target.height(), width:0, backgroundColor: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(string_LIGHTS_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");

				// 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);

		lis.append(playPause);

		//get it goin on, OOOOWWW!
		//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
		}
		if(!$('body').hasClass('siderale')){
			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 paralaxStartY = 350;
    	if($('body').hasClass('siderale')){
    		paralaxStartY = 150;
    	}
        var bgTargY = - w.scrollTop()/4 + paralaxStartY;
        var bgTarg = '50% ' + bgTargY + 'px';
        b.css('backgroundPosition', bgTarg);
    });
}

var equalizeColumns = function(){
	var rowsToEQ = $('#wrapper .row, .promos .row').not('.retail .row, .commentList, .intervention .details, .creators.row, .detail-header');
	var homeCols = $('.homeFirstCol, .homeSecondCol, .homeThirdCol');

	rowsToEQ.each(function(){

		var heights = [];
		var theCols = $(this).find('.col_4, .col_3, .col_8, .col_9').not('.creatorBioRow2 .col_4, .creatorBioRow1 .col_4');
		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 = string_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.split(" | ");//encodeURIComponent(document.title);
			window.open('http://twitter.com/share?url='+loc+'&text='+encodeURIComponent(title[title.length-1])+' @IWC - ', '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

        $("img[alt='MCBE Form Button']").parent().siblings().css({'display':'none'}); // hide the uneeded link

		// homepage marquee
		if($('.slider.homepage-marquee').length > 0){ $('.slider.homepage-marquee').iwcSlider({type:'homepage'}); }

		// family marquee // handle 1 or more sliders per page
		if($('.slider.family-marquee').length > 0){
            //console.log("found " + $('.slider.family-marquee').length + " family sliders")
		    $('.slider.family-marquee').each(function(){
		        $(this).iwcSlider({type:'family'});
		    })
		}

		// detail marquee // handle 1 or more sliders per page
		if($('.slider.detail-marquee').length > 0){
		    //console.log("found " + $('.slider.detail-marquee').length + " detail sliders")
            $('.slider.detail-marquee').each(function(){
                if ($(".article-the-volvo-ocean-race").length > 0){
    		        $(this).iwcSlider({type:'family'});
    		    }else{
    	            $(this).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, .siderale .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 desc = $(this).find("p");
            if (desc.html()) {
                var fullHref =	$(this).find("a").eq(0).attr("href");
                var appendix = 	desc.html().length > 0 ? "...&nbsp;<a>"+string_READ_MORE+"</a>" : "<a>"+string_READ_MORE+"</a>";
                desc.html(desc.html() + appendix);
                desc.truncateBlockAtLine(descTrunc, appendix); // trunc
                desc.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);
		}

	    // open in new window on MCBE form page
        // $('.mcbeform a[href^="' + url_PRIVACY + '"]').live('click', function(e){
        //  e.preventDefault();
        //             window.open(url_PRIVACY, 'IWC Privacy Policy');
        //             return false;
        // });
        //
        //      // open in new window
        //         $('a[href^="' + url_MCBE_RULES + '"]').live('click', function(e){
        //  e.preventDefault();
        //             window.open(url_MCBE_RULES, 'MCBE Contest Rules');
        //             return false;
        // });

		$('.indent p:first-child').prepend('<span class="indentRule"></span>');
		initFormLinks();//bind the form links for overlays


        //This step is for consistency's sake.
        $('.article-the-volvo-ocean-race').addClass('vorParalax');

        // We added in a link to identify the ports in the CMS, now we have to remove them
        $('.article-the-volvo-ocean-race .textContent h4 a').each(function() {
            var t = $(this);
            t.parent().addClass("vorRoute").attr('title',t.attr('href').replace(/[^a-zA-Z0-9_\.]+/g,""));
            t.after(t.text()).remove();
        });

        if($('body').hasClass('vorParalax')){
             $('body').prepend('<div class="portsMap"><img src="' + MEDIA_URL + 'chrome/images/vor/map_middle.png" alt="Port Map"><div id="portsRoutes2" class="portsRoutes"></div><div id="portsRoutes1" class="portsRoutes"></div></div>');
             vorParalaxBG();
        }

        if($('#boatParts').length > 0){
             $('#boatParts').parent().parent().parent(".row").attr({id:"boatContainer"});
             $('#boatParts').boat2();
             $('#boatContainer #prevNext .prev').trigger('click');
        }
	}


	// 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();
	})

	// restrict phone number inputs to just numbers
	$(".contact .phoneNumbers #id_phone_area_code, .contact .phoneNumbers #id_phone_number").keypress(function(event) {
		var charCode = (event.which) ? event.which : event.keyCode;
		//console.log("charCode:" + charCode);
		if ((charCode > 31 && charCode < 48) || (charCode > 57)){
			return false;
		}else{
			return true;
		}
	});


	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 fullText = this.text(); // Only use the text, as HTML tags may break things when splitting out words later on.
		var temp = this.clone();
		$(this).replaceWith(temp);

		var words = fullText.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);

		// totally weird hack to get the siderale form to work correctly
		// WE ARE NOT DOING THIS NOW, BUT I AM LEAVING IT IN THERE IN CASE WE CHANGE OUR MINDS
		// if($('body').hasClass('siderale')){
		// 	formatSideraleForm(this);
		// }

		// 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;
	}
});

var formatSideraleForm = function(sForm){
	var $form = $(sForm);

	$form.find('h2').text(string_CONTACT_SIDERALE); // change header
	$form.find('#id_subject_area').append('<option value="siderale" selected="true">'+string_SIDERALE+'</option>').hide(); // change subject value

	setTimeout(function(){ // hide subject field (the timeout is because there is some js custom formatting)
		$form.find('#selectsubject_area').replaceWith('<span style="display:inline-block;padding:15px 0 7px">'+string_SIDERALE+'</span>');
	}, 50);

	$form.find('li').eq(1).hide(); // hide the 'case'
}

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"});

	// console.log(this.$elmts.popover.find(".modal.contact"));
	// console.log(this.$elmts.popover.find(".modal.contact").length > 0);
	// console.log("DOES IT CONTAIN : " + jQuery.contains(this.$elmts.popover, this.$elmts.popover.find(".modal.contact")))

	if(this.$elmts.popover.find(".modal.contact").length > 0 && this.width<945){
		this.$elmts.popover.width(945);
	}

	// 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(Custom.init){
		Custom.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.variations[hashObj.variation].isStarChart) {
		// console.log("this.variations["+hashObj.variation+"].isStarChart : " +this.variations[hashObj.variation].isStarChart);
		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;
	}
	if(this.variations.length > 1){
		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");
	}

	if(this.variations[this.currentVariation].isStarChart){
		this.$elmts._menu._buttons.view.find("span.detailMenuLabel").text(this.frontBack == "back" ? string_VIEW_NORTH : string_VIEW_SOUTH);
	}
	else{
		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._buttons = {};

	// 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();

	if(!surrogate.variations[surrogate.currentVariation].isStarChart){
		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)
	if(this.variations.length > 1) {
		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._thumbnails = [];
		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("/");
	// console.log("hash[0] : " + hash[0]);
	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() {
	// console.log("this.variations[this.currentVariation].isStarChart : " + this.variations[this.currentVariation].isStarChart);
	if(this.variations[this.currentVariation].isStarChart){
		ret = "#enlargeStarChart";
	}
	else{
		ret = "#enlarge/variation-"+(this.currentVariation+1)+"/"+this.frontBack+"/zoom-"+(this.currentZoomLevel+1);
	}
	return ret;
}

$.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) || ("iPad iPhone iPod").indexOf(navigator.platform) > -1) {
		$(".iwcVideo").each(function() {
			var expID = "bc_"+$(this).attr("id").split("-")[1];
			setTimeout(function() { onTemplateLoaded(expID, true); }, 2000);
		});
	}


});

function onTemplateLoaded(experienceID, bypass) {
	if(bypass) {
		$("#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) {
	if(!this.bc) {
		var surrogate = this;
		this.bc = {
			expID : experienceID,
			exp : brightcove.getExperience(experienceID),
			_modules : {}
		};

		this.bc._modules.videoPlayer = this.bc.exp.getModule(APIModules.VIDEO_PLAYER);
		this.bc._modules.experience = this.bc.exp.getModule(APIModules.EXPERIENCE);
		this.bc._modules.content = this.bc.exp.getModule(APIModules.CONTENT);

		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();
		});

		if($(".article-the-volvo-ocean-race").length == 1){ //loop the VOR video
			this.bc._modules.videoPlayer.addEventListener(BCMediaEvent.PROGRESS, function(event) {
				if (event.position > event.duration - 1) {
			    	surrogate.bc._modules.videoPlayer.seek(0);
			  	}
			});
		}
	}
};


// --- VOR PARALLAX/ROUTE SWITCH ---
var vorParalaxBG = function() {

	var topDist = 15; //How far from top the map comes to a rest
	var topOffset = -75; //How far from the top of the ports section do you stop parallaxing
	var routesOffset = 285; //How far from the top of each route/port does the map overlay transition

	//Naming some jquery objects
    var $w = $(window);
    var $b = $('body');
	var $ports = $('body.en-us h2.pageTitle a[name="Stopovers"], body.zh-cn h2.pageTitle a[name="停靠港口"], body.zh-tw h2.pageTitle a[name="停靠港口"], body.it h2.pageTitle a[name="Sediditappa"], body.de h2.pageTitle a[name="Zwischenstopps"]').parent().parent();
	var $boats = $('body.en-us h2.pageTitle a[name="TheBoats"], body.zh-cn h2.pageTitle a[name="帆船"], body.zh-tw h2.pageTitle a[name="帆船"], body.it h2.pageTitle a[name="LeBarche"], body.de h2.pageTitle a[name="DIEJACHTEN"]').parent().parent();

	var language = 'enus';
	if($("body").hasClass("zh-cn")) language = 'zhcn';
	else if($("body").hasClass("zh-tw")) language = 'zhtw';
	else if($("body").hasClass("it")) language = 'it';
	else if($("body").hasClass("de")) language = 'de';

	var $map = $('.portsMap');

	//Get the y coordinates
	var portsY, boatsY;
	var routeY = new Array();
	var routeName = new Array();

	//Housekeeping stuff...
	if($w.height() < 600) topDist -= 200;
	var currentRoute = -1;
	var oldRoute = -1;
	var routeToggle = 1;

	var calcParalaxBG = function() {

	    preloadRoutes();

		if(boatsY != $boats.offset().top) {
			portsY = $ports.offset().top;
			boatsY = $boats.offset().top;
			$('.vorRoute').each(function(index) {
				routeY[index] = $(this).offset().top;
				// routeName[index] = $(this).attr('title');
			});

			//Manual adjustments to the Y starting points
			routeY[0]-=114;
			routeY[1]-=130;
			routeY[2]-=147;
			routeY[3]-=10;
			routeY[4]-=300;
			routeY[5]-=140;
			routeY[6]-=80;
			routeY[7]-=130;
		}

		//Figure out which routes section we are in
		$.each(routeY,function(index,value) {
			if($w.scrollTop()+routesOffset<routeY[0]) currentRoute = -1;
			if($w.scrollTop()+routesOffset>value) currentRoute = index;
			if($w.scrollTop()+routesOffset>routeY[routeY.length-1]) currentRoute = -1;
		});

		if(currentRoute!=oldRoute) { //Detect if there's been a change of routes
			//console.log("Route change!!");
			if(routeToggle>0) {
				if(routeName[currentRoute]!=undefined) var newBgImg = "url(" + MEDIA_URL + "chrome/images/vor/" + routeName[currentRoute] + "/" + language + ".png)"
				else var newBgImg = "none";
				if(opacitySupport) {
					$("#portsRoutes1").stop().fadeOut();
					$("#portsRoutes2").stop().hide().css("background-image",newBgImg).fadeTo(400,1.0);
				}
				else {
					$("#portsRoutes1").stop().hide();
					$("#portsRoutes2").stop().css("background-image",newBgImg).show();
				}
			} else {
				if(routeName[currentRoute]!=undefined) var newBgImg = "url(" + MEDIA_URL + "chrome/images/vor/" + routeName[currentRoute] + "/" + language + ".png)"
				else var newBgImg = "none";
				if(opacitySupport) {
					$("#portsRoutes2").stop().fadeOut();
					$("#portsRoutes1").stop().hide().css("background-image",newBgImg).fadeTo(400,1.0);
				}
				else {
					$("#portsRoutes2").stop().hide();
					$("#portsRoutes1").stop().css("background-image",newBgImg).show();
				}
			}
			oldRoute = currentRoute;
			routeToggle*=-1;
		}

		//How far the current window is from the "Ports" section
		var top = portsY+topOffset - Math.min($w.scrollTop(),portsY+topOffset);
		var bgTargY = top/5 + topDist;
		var mapTargY = top/5 + topDist;
		var mapTargOp = 1-(top/(portsY+topOffset));

		//How close is the current window is to the bottom of the "Ports" section
		var bottom = $w.scrollTop() - boatsY + 700;
		if (bottom > 0) {
	    	var bgTargY = bottom/-5+topDist;
			var mapTargY = bottom/-5+topDist;
			var mapTargOp = 1-Math.min((bottom/(portsY+topOffset)),1);
		}

		//Move the images
	    $b.css('backgroundPosition', '50% ' + bgTargY + 'px');
		if(opacitySupport) $map.css({top:mapTargY,opacity:Math.pow(mapTargOp,4)});
		else $map.css({top:mapTargY});
	}

	//Preload the images...
    var routeImages = new Array()
    function preloadRoutes() {
      $('.vorRoute').each(function(index) {
          routeName[index] = $(this).attr('title');
          routeImages[index] = new Image();
          routeImages[index].src = MEDIA_URL + "chrome/images/vor/" + routeName[index] + "/" + language + ".png";
      });
    }


    // $w.load(function(){
    //  calcParalaxBG();
    // });

    //calcParalaxBG();

    $w.scroll(function(){
		calcParalaxBG();
    });
}

// --- VOR BOATS SVG ---
$.fn.boat2 = function(opts){
	//LOCAL VARS
	var defaults = {
		dur : 200
	}

	var options = $.extend(defaults, opts);
	var cParts = this.find('li');
	var	partsBox = $('<div id="boatPartsBox"></div>');
	var	frontBack = $('');
	var washout = $('<li class="washout"></li>');
	var copyBox = $('<div class="boatCopy"></div>');
	var counter = $('<div class="hr"></div><p class="counter"><span class="incrementNum">1</span> '+ string_OF +' <span class="totalNum">100</span></p>');
	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: 480, y: 650}
	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){
			// console.log("onPartClick");
			showPartInfo(ind);
		}
	}

	bg.append("<img class='back' src='"+ MEDIA_URL + "chrome/images/vor/volvo_open_70.jpg' alt='' />");
	bg.append("<img class='front' src='"+ MEDIA_URL + "chrome/images/vor/volvo_open_70.jpg' alt='' />");

	var onPrevNextClick = function(e){
		var newPart = 0;
		//console.log($(e.target).attr('href'));
		//console.log($(e.target).attr('href').split("#")[1]);
		switch($(e.target).attr('href').split("#")[1]){
			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){
			// console.log("onPrevNextClick");
			showPartInfo(newPart);
			fadeInPart($(cParts.get(newPart)));
		}

		if(newPart >= 4){
			if(opacitySupport){
				bg.find('img.front').animate({'opacity':'0'});
			}
			else{
				bg.find('img.front').hide();
			}
			toggleFrontBackLinks("front");
		}
		else{
			if(opacitySupport){
				bg.find('img.front').animate({'opacity':'1'});
			}
			else{
				bg.find('img.front').show();
			}
			toggleFrontBackLinks("back");
		}
		updateCounter(newPart, copyList.length);
	}

	// METHODS
	var updateCounter = function(num, totalNum){
		counter.find('span.incrementNum').text(num + 1);
		counter.find('span.totalNum').text(totalNum);
	}

	var toggleFrontBackLinks = function(whichIsActive){
	}

	var showPartInfo = function(ind){
		var pToShow = $(copyList.get(ind));
		var yOffset = 6;
		var xOffset = 22;
		copyBox.attr('class', 'boatCopy c_' + ind);
		copyList.hide().filter(pToShow).show();
		prevNext.show();

		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');
			//$('#sideraleContainer .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 = 'L180 '+ (oy - 20);
		var p4 = 'L180 '+ ty;
		var p5 = 'L'+ tx + ' ' + ty;

		if (tx > ox) {
			// draw to right of image
			p3 = 'L' + (ox + 300) + ' ' + (oy - 20);
			p4 = 'L' + (ox + 300) + ' ' + 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);
	}


	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(counter).append(copyList).insertAfter(this).hide();
	bg.insertBefore(this);

	// raphHolder.height(this.height()).insertBefore(this);
	raphHolder.height(650).insertBefore(this);
	paper = Raphael("raphHolder", raphHolder.width(), raphHolder.height());

	cParts.hoverIntent(hoverConfig).css({"opacity":"0", "filter":"alpha(opacity=0)"}).bind('click', function(){
		onPartClick(this);
	}).each(function(i){
		$(this).addClass('c_part_' + i);
	});
	copyBox.fadeIn();

	frontBack.find('a').bind('click', function(e){
	});

	// $('#prevNext .prev').trigger('click');
	return this.each(function(){});
}

/*
The following is a hack for the VOR iframe game, so that the iframe's height
can automatically be resized when the content changes. This hack should be
be removed if/when the game is taken off the site.
 */
function autoResize(height) {
    $('body #wrapper iframe').css(height+'px');
}




/*
 * 	IWC.com
 * 	sidereal.js created on May 31, 2011
 * 	by Greg Martin @ Odopod
 *
 */

/*///////////////////////////

	BEGIN - SIDERALE JS

////////////////////////////*/
 $(document).ready(function() {
 	if($("body").hasClass("siderale")){
	 	var creatorBioRow1 = new CreatorExpando('.siderale .creatorBioRow1', 0, ".siderale .expandCollapseControls1");
	  	var creatorBioRow2 = new CreatorExpando('.siderale .creatorBioRow2', 0, ".siderale .expandCollapseControls2");

		this.headShotsButtons = $('.headShotWrapper', '.creatorHeadRow1').bind('click', function(e){
			e.preventDefault();
			if(creatorBioRow1.element.hasClass("collapsed")){
				creatorBioRow1.expand();
			}
		});

		this.headShotsButtons = $('.headShotWrapper', '.creatorHeadRow2').bind('click', function(e){
			e.preventDefault();
			if(creatorBioRow2.element.hasClass("collapsed")){
				creatorBioRow2.expand();
			}
		});

		var starChart = new WatchDetail([{
			thumbnail : MEDIA_URL+"chrome/images/siderale/starchart/north_small.gif",
			fronts : [MEDIA_URL+'chrome/images/siderale/starchart/north_large.gif', MEDIA_URL+'chrome/images/siderale/starchart/north_medium.gif',MEDIA_URL+'chrome/images/siderale/starchart/north_small.gif'],
			backs : [MEDIA_URL+'chrome/images/siderale/starchart/south_large.gif', MEDIA_URL+'chrome/images/siderale/starchart/south_medium.gif',MEDIA_URL+'chrome/images/siderale/starchart/south_small.gif'],
			title : "Star Chart",
			isStarChart : true
		}]);

		$('a.enlargeStarChart').bind("click", function(event) {
			event.preventDefault();
			starChart.open();
		});

		var watchDetail = new WatchDetail([{
			//'path/to/thumbnail.jpg',
			thumbnail : MEDIA_URL+'chrome/images/siderale/enlarge/front_end_small.jpg',
			// fronts : ['path/to/front/large.jpg', 'path/to/front/medium.jpg', 'path/to/front/small.jpg']
			fronts : [MEDIA_URL+'chrome/images/siderale/enlarge/front_end_large.jpg', MEDIA_URL+'chrome/images/siderale/enlarge/front_end_medium.jpg', MEDIA_URL+'chrome/images/siderale/enlarge/front_end_small.jpg'],
			//'path/to/back/large.jpg', 'path/to/back/medium.jpg', 'path/to/back/small.jpg'],
			backs : [MEDIA_URL+'chrome/images/siderale/enlarge/back_end_large.jpg', MEDIA_URL+'chrome/images/siderale/enlarge/back_end_medium.jpg', MEDIA_URL+'chrome/images/siderale/enlarge/back_end_small.jpg'],
			title : "Protuguese Sid&eacute;rale Scafusia"
		}]);

		$("a.enlarge").bind("click", function(e) {
			e.preventDefault();
			watchDetail.open();
		});

		$('a.scrollTo').bind('click', function(e){
			e.preventDefault();
			scrollTo($(this));
		});

		$(".watch360").watch360();

		$(".watchImageSlider").each(function(){
			new WatchImageSlider($(this));
		});

		if(document.getElementById('sideraleParts')){
			$('#sideraleParts').siderale2();
			$('.siderale #prevNext .prev').trigger('click');
		}

		var viewChartLink = new viewChartHighlight($(".siderale .chartCustomization .boxLinkContainer .boxArrowLink"));
		var viewChartTextLink = new viewChartHighlight($(".siderale .chartCustomization .viewChartTextLink"));
	}
 });

 var viewChartHighlight = function(element){
 	element.bind('mouseover', function(e){
 		e.preventDefault();
		$(".siderale .chartCustomization .bgImage").addClass("highlighted");
	});
	element.bind('mouseout', function(e){
		e.preventDefault();
		$(".siderale .chartCustomization .bgImage").removeClass("highlighted");
	});
 }

 /*///////////////////////////

	START - EXPAND COLLAPSE

////////////////////////////*/

var CreatorExpando = function(el, theLimit, btnRef){
	this.element = $(el);
	this.limit = theLimit;
	this.lis = $('li', this.element);
	this.button = $(btnRef);
	this.downText = this.button.data('collapse-text');
	this.upText = this.button.text();

	this.element.addClass("expanded");

	var that = this;

	if(this.lis.length > this.limit){
		this.button.css({display:'block'});
		that.collapse();
	}
}
CreatorExpando.prototype.collapse = function(){
	var parentObj = this;
	console.log("collapsing : " + parentObj.element.attr("class"));
	parentObj.element.removeClass("expanded").addClass("collapsed");
	parentObj.lis.each(function(i){
		if(i>parentObj.limit-1){
            if(jQuery.support.opacity && !$.browser.msie){
				$(this).animate({"height":"0px", "opacity":"0"}, 200, function(){
					console.log("COLLAPSE FINISHED : " + $(this).attr("class"));
				});
			}
			else{
				$(this).hide();
				$(this).css({"height":"0px"});
			}
		}
	});
	console.log("collapsing : " + parentObj.element.attr("class"));


	parentObj.button.unbind('click');
	parentObj.button.bind('click', function(e){
		e.preventDefault();
		parentObj.expand();
		scrollTo($(this));
	}).removeClass('down').text(this.upText);

}
CreatorExpando.prototype.expand = function(){
	var parentObj = this;

	parentObj.element.removeClass("collapsed").addClass("expanded");

    if(jQuery.support.opacity && !$.browser.msie){
		parentObj.lis.animate({"height":"300px", "opacity":"1"}, 200, function(){
			console.log("EXPAND FINISHED : " + $(this).attr("class"));
		});
	}
	else{
		parentObj.lis.show();
		//$(this).css({"height":"300px"});
		parentObj.lis.css({"height":"300px"});
	}

	parentObj.button.unbind('click');
	parentObj.button.bind('click', function(e){
		e.preventDefault();
		parentObj.collapse();
		scrollTo($(this));
	}).addClass('down').text(this.downText);
}

/*///////////////////////////

	START - SCROLL TO

////////////////////////////*/

var scrollTo = function(elementClicked) {
		var elementHref = $(elementClicked).attr('href');
	 	var destination = $(elementHref).offset().top;
	  	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 500 );
   	return false;
}

/*///////////////////////////

	START - DRAG SLIDER

////////////////////////////*/

function SlideControl($rail, $handle, opts) {
	var th = this, sc = "slidecontrol", evtNS = sc+"-"+Math.floor((Math.random()*1E4)).toString(16), startDrag, stopDrag;

	$.extend(
		th,
		{
			initialValue : 0,
			steps : 0, // How many steps should there be between the start and end?
			orientation : "h",
			reverse : false,
			animateSlide : true,
			snapToStepIncrements : 0,
			isThrowable: false
		},
		opts,
		{
			$rail : $rail,
			inMotion : false,
			// isCheckingIncrementSnap : false,
			$currentStep:0,
			$lastDragPos: 0,
			$dragTimer: null,
			eventNamespace : evtNS,
			evts : {
				mMv : "mousemove."+evtNS,
				bDr : "beforeDrag."+sc,
				aDr : "afterDrag."+sc,
				rCl : "railClick."+sc,
				uPo : "updatePosition."+sc
			}
		}
	);

	th.orientation = th.orientation === "v" ? "v" : "h";

	th.$handle = !!$handle ? $handle : $("<span/>", {"class" : "handle"});
	th.$rail.has(th.$handle.get(0)) || th.$rail.append(th.$handle);

	th.$handle.css({
		"position" : "absolute",
		"MozUserSelect" : "none",
		"WebkitUserSelect": "none",
		"userSelect": "none"
	}).bind({
		"selectstart" : function() { return false; },
		"dragstart" : function() { return false; },
		"mousedown" : function(e) { startDrag(e); }/*,
		"mouseup" : function(e) { stopDrag(e); }*/
	});

	th.$rail.css({position:"relative"}).bind({
		"click" : function(e) {
			if(!th.inMotion) {
				// if(!th.isCheckingIncrementSnap){
					th.$rail.trigger(th.evts.rCl);
					if(th.snapToStepIncrements > 0){
						th.checkSlideSnapIncrement();
					}
					else{
						th.slideToPos(th.orientation === "h" ? e.pageX-th.$rail.offset().left : e.pageY-th.$rail.offset().top, true);
					}
				// }
			}
		}
	});

	startDrag = function(e) {
		th.inMotion = true;
		e.stopPropagation();
		th.$rail.trigger(th.evts.bDr);
		th.$handle.addClass("hover");

		$(document.body).bind('mouseup', stopDrag);

		//th.$rail.bind("mouseleave", function(e) { stopDrag(e); });
		$(document).bind(th.evts.mMv, function(e) {
			th.slideToPos(th.orientation === "h" ? e.pageX-th.$rail.offset().left : e.pageY-th.$rail.offset().top, false);
		});

		if (th.isThrowable) {
			th.$dragTimer = setInterval(function() {
				if (th.isThrowable) {
					th.$lastDragPos = parseInt(th.$handle.css('left'));
				}
			}, 100);
		}

		return false;
	};

	stopDrag = function(e) {

		$(document).unbind(th.evts.mMv);
		$(document.body).unbind('mouseup', stopDrag);
		//th.$rail.unbind("mouseleave");

		th.$handle.removeClass("hover");
		th.$rail.trigger(th.evts.aDr);

		if (th.isThrowable) {

			clearInterval(th.$dragTimer);
			th.$dragTimer = null;

			var currentDragPos = parseInt(th.$handle.css('left'));
			var speed = currentDragPos - th.$lastDragPos;

			// dragged far enough?
			if (Math.abs(speed) > 10) {
				// animate to new position
				th.slideToPos(currentDragPos + speed, true, 'easeOutSine');
				// th.dragComplete();
				return false;
			}

		}

		th.slideToPos(th.orientation === "h" ? e.pageX-th.$rail.offset().left : e.pageY-th.$rail.offset().top, false);
		th.dragComplete();

		return false;
	};

	th._updateSize();
};
SlideControl.prototype.dragComplete = function(){
	var th = this;
	th.checkSlideSnapIncrement();
	th.inMotion = false;
};
SlideControl.prototype.checkSlideSnapIncrement = function(){
	var th = this;
	var checkNum = th.steps/th.snapToStepIncrements; //(th.railSize/th.stepSize)/th.steps;
	if(th.snapToStepIncrements > 0){
		for (var i = 1; i <= checkNum; i++){
			if(th.$currentStep < (i * th.snapToStepIncrements) && th.$currentStep > ((i-1) * th.snapToStepIncrements)){
				if( th.$currentStep > ((i-1) * th.snapToStepIncrements+ (th.snapToStepIncrements/2)) ){
					th.slideToStep((i * th.snapToStepIncrements), true);
				}
				else{
					th.slideToStep(((i-1) * th.snapToStepIncrements), true);
				}
				return;
			}
		}
	}
}
SlideControl.prototype.slideToPos = function(pos, animate, easing) {
	var th = this;

	animate = animate === false ? false : true;
	if (typeof(easing) == 'undefined') easing = 'linear';

	// Parse and validate pos
	pos < 0 && (pos = 0);
	pos >= th.railSize && (pos = th.railSize);

	th.steps && (pos = Math.round(pos/th.stepSize) * th.stepSize);
	/*
	th.$handle.animate(
		th.orientation === "h" ? {left:pos} : {top:pos},
		animate && th.animateSlide ? 200 : 0,
		"linear",
		{step: function(now, fx) {
			if(now = Math.round(pos/th.stepSize) * th.stepSize){
				console.log("now : " + now);
			}
		}
		,complete: function() {
			th.$currentStep = Math.round(pos/th.stepSize);
			// console.log("$currentStep : " + th.$currentStep);
			th.$rail.trigger({
				"type" : th.evts.uPo,
				"position" : pos,
				"step" : th.$currentStep//Math.round(pos/th.stepSize)
			});
		}}
	);
	*/
	th.$handle.animate(
		th.orientation === "h" ? {left:pos} : {top:pos},
		{duration:animate && th.animateSlide ? 300 : 0,
		easing: easing,
		step: function(now, fx) {
			// console.log("now : " + Math.round(now));
			// console.log("tgtPos : " + Math.round(Math.round(pos/th.stepSize) * th.stepSize));
			th.inMotion = true;
			th.$currentStep = Math.round(now/th.stepSize);
			th.$rail.trigger({
				"type" : th.evts.uPo,
				"position" : now,
				"isComplete" : false,
				"step" : th.$currentStep
			});
		}
		,complete: function() {
			th.$currentStep = Math.round(pos/th.stepSize);
			// console.log("$currentStep : " + th.$currentStep);
			th.inMotion = false;
			th.$rail.trigger({
				"type" : th.evts.uPo,
				"position" : pos,
				"isComplete" : true,
				"step" : th.$currentStep//Math.round(pos/th.stepSize)
			});
		}}
	);
	return this;
};
SlideControl.prototype.slideToStep = function(step, animate) {
	var th = this;
	this.slideToPos(step*(this.steps ? this.stepSize : 1), animate);

	return this;
};
SlideControl.prototype._updateSize = function() {
	var th = this;

	th.railSize = (th.orientation === "h" ? th.$rail.width() : th.$rail.height())-1;
	th.steps && (th.stepSize = th.railSize / th.steps);

	return this;
};

/*///////////////////////////

	END - DRAG SLIDER

////////////////////////////*/

/*///////////////////////////

	START - WATCH 360

////////////////////////////*/

function Preloader(urlArray, callback, opts) {
	var th = this;
	$.extend(
		th,
		{
			$target : $(document), // Target on which all events should trigger
			onFinishOne : null, // Optional callback to fire whenever an image in the array finishes loading
			checkFilesize : true, // Should the filesize check be employed before the images are loaded?
			startNow : true, // True if the Preloader should start immediately, false if it should wait
			loadMethod : "inOrder" // or "interpolate", or "middleOut", or "stepped/n", where n is an integer
		},
		opts,
		{
			urls : urlArray,
			onFinishAll : callback,
			loaderQueue : [],
			errors : [],
			completed : [],
			totalBytes : 0,
			completedBytes : 0,
			state : "initializing",
			evts : {
				bFs : "beforeFilesize.preloader",
				aFs : "afterFilesize.preloader",
				pFs : "filesizeProgress.preloader",
				bLo : "beforeLoad.preloader",
				aLo : "afterLoad.preloader",
				pLo : "loadProgress.preloader"
			}
		}
	);

	th.startNow && th.start();
}

// Preloader.start() launches the entire preloading process, including the filesize pre-check.
Preloader.prototype.start = function() {
	var th = this, filesizeQueue, tempArray, a, b, c;

	$.each(th.urls, function(i, url) {
		th.loaderQueue[i] = {
			originalIndex : i,
			url : th.urls[i],
			filesize : 0
		};
	});

	// Reorganize this.loaderQueue based on this.loadMethod
	if(th.loadMethod === "interpolate") {
		tempArray = th.loaderQueue;
		th.loaderQueue = [tempArray.splice(0,1)[0], tempArray.splice(-1,1)[0]];
		a = 1;
		b = 2;
		do {
			(a%2) && th.loaderQueue.push(tempArray.splice(Math.floor((tempArray.length/b)*a), 1)[0]);
			a++;
			if(a >= b) {
				a = 1;
				b *= 2;
			}
		} while(tempArray.length);
	} else if(th.loadMethod === "middleOut") {
		tempArray = th.loaderQueue;
		th.loaderQueue = [];
		do {
			th.loaderQueue.push(tempArray.splice(Math.floor((tempArray.length-1)/2), 1)[0]);
		} while(tempArray.length);
	} else if(th.loadMethod.split("/")[0] === "stepped") {
		tempArray = th.loaderQueue;
		th.loaderQueue = [];
		a = 0;
		b = th.loadMethod.split("/").length > 1 && parseInt(th.loadMethod.split("/")[1]) > 0 ? parseInt(th.loadMethod.split("/")[1]) : 2;
		c = 0;
		do {
			th.loaderQueue.push(tempArray[a]);
			a += b;
			if(a >= tempArray.length) {
				a = ++c;
			}
		} while(th.loaderQueue.length < tempArray.length);
	}


	if(th.checkFilesize) {
		filesizeQueue = th.loaderQueue;
		th.loaderQueue = [];
		th.state = "filesize_checking";
		th.$target.trigger({type:th.evts.bFs, preloaderData:th._getDataObject()});
		sizeLoop(0);
	} else {
		loadEm();
	}
	return th;

	// Internal function to handle loading of images
	function loadEm() {
		var dfrs=[], dfr;

		th.state = "loading";
		th.$target.trigger({type:th.evts.bLo, preloaderData:th._getDataObject()});

		while(th.loaderQueue.length) {
			var thisImg = $("<img/>", {
				load : function() { doneOne(1, $(this).data("imgObj")); $(this).removeData("imgObj"); },
				error : function() { doneOne(0, $(this).data("imgObj")); }
			}).data("imgObj", th.loaderQueue.splice(0,1)[0]);
			thisImg.attr("src", thisImg.data("imgObj").url)
		}

		function doneOne(g, imgObj) {
			var dataObj;
			// Push this image to one array or the other depending on the result of its load
			if(g) {
				th.completed.push(imgObj);
				th.completedBytes += imgObj.size;
			} else {
				th.errors.push(imgObj);
			}
			dataObj = th._getDataObject(imgObj);
			th.$target.trigger({type:th.evts.pLo, preloaderData:dataObj});
			$.isFunction(th.onFinishOne) && th.onFinishOne(dataObj);

			if(th.completed.length + th.errors.length === th.urls.length) {
				doneAll();
			}
		}

		function doneAll() {
			var dataObj;
			th.state = "finished";

			dataObj = th._getDataObject();
			th.$target.trigger({type:th.evts.aLo, preloaderData:dataObj});
			$.isFunction(th.onFinishAll) && th.onFinishAll(dataObj);
		}
	};

	// Internal loopable function to check filesizes with XHR Head requests
	function sizeLoop(index) {
		var xhr = new XMLHttpRequest(), byteSize;
		// Use the XHR object to open a HEAD request to this url. Third argument specifies that this is an asynchronous request.
		xhr.open('HEAD', filesizeQueue[index], 1);
		// Set the xhr.onreadystatechange property to a function call
		xhr.onreadystatechange = function() {
			var imgObj;
			if(xhr.readyState == 4) {
				// 200 status means everything is good
				if(xhr.status == 200) {
					// Get the byteSize and dump it into an object and append it to this.pending
					byteSize = parseInt(xhr.getResponseHeader('Content-Length'), "10");
					imgObj = filesizeQueue[index];
					imgObj.filesize = byteSize;
					th.loaderQueue.push(imgObj);
					// Track total running bytesize for all images
					th.totalBytes += byteSize;
				// Any other status means this image can't be loaded properly. Error.
				} else {
					th.errors.push(filesizeQueue[index]);
				}
				th.$target.trigger({type:th.evts.pFs, preloaderData:th._getDataObject(imgObj)});

				// Check if we should continue looping
				if(++index < filesizeQueue.length) {
					sizeLoop(index);
				} else {
					th.$target.trigger({type:th.evts.aFs, preloaderData:th._getDataObject()});
					loadEm();
				}
			}
		};
		// Execute the XHR.
		xhr.send(null);
	};
};

// Preloader._getDataObject() is a "private" function to assemble an object containing data about the Preloader's current state.
Preloader.prototype._getDataObject = function(thisImg) {
	var th=this;
	return {
		"state" : th.state,
		"totalImages" : th.urls.length,
		"totalBytes" : th.totalBytes,
		"totalErrors" : th.errors.length,
		"completedImages" : th.completed.length,
		"completedBytes" : th.completedBytes,
		"latestImage" : !!thisImg ? thisImg : false
	};
}

function Watch360($container, imageUrlArray, opts) {
	var th = this, tempArray, a, b, oneLoaded, enoughLoaded, allLoaded;

	$.extend(
		th,
		{
			$el : $container,
			currentImage : null,
			numToPreload : 0.5 // Number of images to preload before initializing, or percentage (ie 0.5) of images to load
		},
		opts,
		{
			imageUrls : imageUrlArray,
			readyToGo : false
		}
	);

	// If th.numToPreload is less than one, it's actually percentage.
	th.numToPreload = Math.round(th.numToPreload * (th.numToPreload < 1 ? imageUrlArray.length : 1));

	th.$imgContainer = th.$el.find(".imageContainer").eq(0);
	th.$imgContainer.find("img").eq(0).addClass("temp");
	th.$sliderContainer = th.$el.find(".slider").eq(0);

	// Create a placeholder span for each image
	$.each(th.imageUrls, function() {
		th.$imgContainer.append($("<span/>", {"class":"placeHolder"}));
	});

	oneLoaded = function(imgObject) {
		var $img = $("<img/>", {"class":"angle", "src":imgObject.url});
		th.$imgContainer.children().eq(imgObject.originalIndex).replaceWith($img);
	};

	allLoaded = function() {};

	enoughLoaded = function(pD) {
		var $handle, label1, label2, label3;

		th.readyToGo = true;

		th.$imgContainer.find("img.temp").remove();
		th.$imgContainer.find("img.angle:eq(0)").addClass("selected");

		// Set up slider
		label1 = $("<span/>", {"class":"label label-0","html":"0&deg;"}).hide().appendTo(th.$sliderContainer);
		label2 = $("<span/>", {"class":"label label-180","html":"180&deg;"}).hide().appendTo(th.$sliderContainer);
		label3 = $("<span/>", {"class":"label label-360","html":"360&deg;"}).hide().appendTo(th.$sliderContainer);

		$handle = $("<span/>", {"class":"handle", "text":"0"}).hide().appendTo(th.$sliderContainer);

		$handle.add(label1).add(label2).add(label3).fadeIn(200);

		th.slider = new SlideControl(th.$sliderContainer, $handle, {
			steps : 72,
			isThrowable: true
		});
		// Bind to slider events
		th.slider.$rail.bind("updatePosition.slidecontrol", function(e) {
			th.slider.$handle.text(e.step*5);
			th.scrubToImage(e.step);
		})
	};

	// Set up preloader
	th.preloader = new Preloader(th.imageUrls, allLoaded, {
		$target : th.$el,
		checkFilesize : false,
		loadMethod : "stepped/2",
		onFinishOne : function(pD) {
			oneLoaded(pD.latestImage);
			!th.readyToGo && pD.completedImages+pD.totalErrors >= th.numToPreload && enoughLoaded(pD);
		}
	});
}
Watch360.prototype.scrubToImage = function(index) {
	var th = this, children = th.$imgContainer.children(), newGuy;

	if(!children.eq(index).is("img")) {
		index++;
	}
	newGuy = children.eq(index);

	if(!newGuy.hasClass("selected")) {
		children.filter(".selected").removeClass("selected");
		newGuy.addClass("selected");
	}
	th.currentImage = index;
	return this;
}

$.fn.watch360 = function() {
	$(this).each(function() {
		var img = $(this).find("img"), srcFragment, i, urls = [];
		srcFragment = $(this).find("img").attr("src").split("_000.png")[0];
		for(i=0; i<=360; i+=5) {
			urls.push(srcFragment+"_"+padStringToLength(i, 3, "0", true)+".png")
		}

		new Watch360($(this), urls, {

		});
	});
}

function padStringToLength(str,len,pad,prepend) {
	str = typeof str == "string" ? str : str.toString();
	pad = typeof pad == "string" ? pad : "0";
	while(str.length < len) {
		str = !prepend ? (str + pad) : (pad + str);
	}
	return str;
}

/*///////////////////////////

	END - WATCH 360

////////////////////////////*/

/*///////////////////////////

	START - WATCH IMAGE SLIDER

////////////////////////////*/

function WatchImageSlider(element) {
	var wis = this;
	wis.steps = 36;
	wis.snapIncrements = 18;

	// console.log(element);
	wis.sliderContainer = element.find(".slider").eq(0);
	wis.imgContainer = element.find(".imageContainer").eq(0);
	wis.copyContainer = element.find(".copyContainer").eq(0);

	wis.imgContainer.find('img').each(function(){
		if(!$(this).hasClass('image-0')){
			if(jQuery.support.opacity){
				$(this).animate({ "opacity": "0"}, 500, function(){

				});
			}
			else{
				$(this).hide();
			}
		}
	});

	wis.copyContainer.find('.copyBlock').each(function(){
		if(!$(this).hasClass('copyBlock-0')){
			if(jQuery.support.opacity){
				$(this).animate({ "opacity": "0"}, 500, function(){

				});
			}
			else{
				$(this).hide();
			}
		}
	});

    var headings = wis.copyContainer.find('h1');

	label1 = $("<span/>", {"class":"label label-0","html":$(headings[0]).text()}).hide().appendTo(wis.sliderContainer);
	label2 = $("<span/>", {"class":"label label-1","html":$(headings[1]).text()}).hide().appendTo(wis.sliderContainer);
	label3 = $("<span/>", {"class":"label label-2","html":$(headings[2]).text()}).hide().appendTo(wis.sliderContainer);

	wis.handle = $("<span/>", {"class":"handle", "text":""}).hide().appendTo(wis.sliderContainer);
	wis.handleSprite = $("<span/>", {"class":"circleSprite"}).appendTo(wis.handle);

	wis.handle.add(label1).add(label2).add(label3).fadeIn(200);

	wis.slider = new SlideControl(wis.sliderContainer, wis.handle, {
		steps : wis.steps,
		snapToStepIncrements : wis.snapIncrements
	});

	//Bind Previous and next Buttons
	$('.sliderButton').bind('click', function(e){
		e.preventDefault();
		if($(this).hasClass('previous')){
			var prevStep = wis.slider.$currentStep - wis.slider.snapToStepIncrements;
			wis.slider.slideToStep(prevStep, true);
		}
		else{
			var nextStep = wis.slider.$currentStep + wis.slider.snapToStepIncrements;
			wis.slider.slideToStep(nextStep, true);
		}
	});

	// Bind to slider events
	wis.slider.$rail.bind("updatePosition.slidecontrol", function(e) {
		wis.scrubToImage(e);
	})
}
WatchImageSlider.prototype.scrubToImage = function(e) {
	var imageNum = 0;
	var wis = this;

	var index = e.step;
	var isComplete = e.isComplete;

	if(index != 0){
		if(jQuery.support.opacity){
			$('.watchImageSlider .handleIntroText').css({"opacity":"0"});
		}
		else{
			$('.watchImageSlider .handleIntroText').hide();
		}
	}
	else{
		if(jQuery.support.opacity){
			$('.watchImageSlider .handleIntroText').css({"opacity":"1"});
		}
		else{
			$('.watchImageSlider .handleIntroText').show();
		}
		// $('.watchImageSlider .handleIntroText').stop().animate({opacity:1}, 0);
	}

	var newXPos = -(index * 27);
	wis.handleSprite.css({"background-position":newXPos});

	if(!wis.slider.inMotion && isComplete){
		wis.showCopyBlock(index);
	}

	if(index <= wis.snapIncrements){
		imageNum = 1;
	}
	else if(index > wis.snapIncrements && index <= (wis.snapIncrements*2)){
		imageNum = 2;
		index = index-wis.snapIncrements;
	}
	else if(index > (wis.snapIncrements*2) && index <= (wis.snapIncrements*3)){
		imageNum = 3;
		index = index - (wis.snapIncrements*2);
	}

	var currImgOpacity = roundNumber($(wis.imgContainer).find('img.image-'+imageNum).css('opacity'), 1);
	var newImgOpacity = roundNumber(Number(0)+Number(index*(1/wis.snapIncrements)), 1);
	// console.log(imageNum);
	// console.log("currImgOpacity : "+currImgOpacity);
	// console.log("newImgOpacity : "+newImgOpacity);

	// $(wis.imgContainer).find('img').filter(function(index){
			// return index > (imageNum);
	// }).css('opacity', 0);
	if(currImgOpacity != newImgOpacity){
		if(jQuery.support.opacity){
			$(wis.imgContainer).find('img.image-'+imageNum).css({'opacity': newImgOpacity, "filter":"alpha(opacity="+newImgOpacity+")"});
		}
		else{
			if(newImgOpacity > 0.5){
				$(wis.imgContainer).find('img.image-'+imageNum).show();
			}
			else{
				$(wis.imgContainer).find('img.image-'+imageNum).hide();
			}
		}
	}

	return this;
}
WatchImageSlider.prototype.showCopyBlock = function(index){
	var wis = this;
	var copyIndex = 0;

	if(index < wis.snapIncrements){
		copyIndex = 0;
	}
	else if(index >= wis.snapIncrements && index < (wis.snapIncrements*2)){
		copyIndex = 1;
	}
	else if(index >= (wis.snapIncrements*2) && index < (wis.snapIncrements*3)){
		copyIndex = 2;
	}
	else if(index == (wis.snapIncrements*3)){
		copyIndex = 3;
	}
	wis.copyContainer.find('.copyBlock').each(function(){
		if(!$(this).hasClass('copyBlock-'+copyIndex)){
			if(jQuery.support.opacity){
				$(this).animate({ "opacity": "0"}, 0);
			}
			else{
				$(this).hide();
			}
		}
		else{
			if(jQuery.support.opacity){
				$(this).animate({ "opacity": "1"}, 0);
			}
			else{
				$(this).show();
			}
		}
	});
}

/*///////////////////////////

	END - WATCH IMAGE SLIDER

////////////////////////////*/

/*///////////////////////////

	START - FEATURES SVG

////////////////////////////*/

$.fn.siderale2 = function(opts){
	//LOCAL VARS
	var defaults = {
		dur : 200
	}
	var options = $.extend(defaults, opts);
	var cParts = this.find('li');
	var	partsBox = $('<div id="sideralePartsBox"></div>');
	var	frontBack = $('<p class="frontBack"><a href="#" class="frontLink">'+string_VIEW_FRONT+'</a><a href="#" class="backLink">'+string_VIEW_BACK+'</a></p>');
	var washout = $('<li class="washout"></li>');
	var copyBox = $('<div class="sideraleCopy"></div>');
	var counter = $('<p class="counter"><span class="incrementNum">1</span> '+ string_OF +' <span class="totalNum">100</span></p>');
	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: 220, y: 550}
	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);
		}
	}

	bg.append("<img class='back' src='"+ MEDIA_URL + "chrome/images/siderale/features/siderale_features_watch_back.jpg' alt='' />");
	bg.append("<img class='front' src='"+ MEDIA_URL + "chrome/images/siderale/features/siderale_features_watch_front.png' alt='' />");

	var onPrevNextClick = function(e){
		var newPart = 0;
		console.log($(e.target).attr('href'));
		console.log($(e.target).attr('href').split("#")[1]);
		switch($(e.target).attr('href').split("#")[1]){
			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)));
		}

		if(newPart >= 4){
			if(jQuery.support.opacity){
				bg.find('img.front').animate({'opacity':'0'});
			}
			else{
				bg.find('img.front').hide();
			}
			toggleFrontBackLinks("front");
		}
		else{
			if(jQuery.support.opacity){
				bg.find('img.front').animate({'opacity':'1'});
			}
			else{
				bg.find('img.front').show();
			}
			toggleFrontBackLinks("back");
		}
		updateCounter(newPart, copyList.length);
	}

	// METHODS
	var updateCounter = function(num, totalNum){
		counter.find('span.incrementNum').text(num + 1);
		counter.find('span.totalNum').text(totalNum);
	}

	var toggleFrontBackLinks = function(whichIsActive){
		if(whichIsActive == "front"){
			frontBack.find('a.backLink').css({"color":"#7f7f7f"});
			frontBack.find('a.frontLink').css({"color":"#cea001"});
		}
		else{
			frontBack.find('a.frontLink').css({"color":"#7f7f7f"});
			frontBack.find('a.backLink').css({"color":"#cea001"});
		}
	}

	var showPartInfo = function(ind){
		var pToShow = $(copyList.get(ind));
		var yOffset = 6;
		var xOffset = 22;
		copyBox.attr('class', 'sideraleCopy 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');
			$('#sideraleContainer .pullQuote').hide();
		}

		paper.clear();

		var l = paper.path('M'+ ox + '  ' + oy);

		l.attr({
			stroke:'#cea001',
			'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;

		if (tx > ox) {
			// draw to right of image
			p3 = 'L' + (ox + 190) + ' ' + (oy - 20);
			p4 = 'L' + (ox + 190) + ' ' + 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(counter).append(copyList).insertAfter(this).hide();
	bg.insertBefore(this);
	// raphHolder.height(this.height()).insertBefore(this);
	raphHolder.height(550).insertBefore(this);
	paper = Raphael("raphHolder", raphHolder.width(), raphHolder.height());

	cParts.hoverIntent(hoverConfig).css({"opacity":"0", "filter":"alpha(opacity=0)"}).bind('click', function(){
		onPartClick(this);
	}).each(function(i){
		$(this).addClass('c_part_' + i);
	});
	copyBox.fadeIn();

	frontBack.find('a').bind('click', function(e){
		e.preventDefault();
		var btn = $(this);

		if(btn.hasClass('frontLink')){
			showPartInfo(0);
			fadeInPart($(cParts.get(0)));
			if(jQuery.support.opacity){
				bg.find('img.front').animate({'opacity':'1', "filter":"alpha(opacity=1)"});
			}
			else{
				bg.find('img.front').show();
			}
			toggleFrontBackLinks("back");
			updateCounter(0, copyList.length);
		}
		else{
			showPartInfo(4);
			fadeInPart($(cParts.get(4)));
			if(jQuery.support.opacity){
				bg.find('img.front').animate({'opacity':'0', "filter":"alpha(opacity=0)"});
			}
			else{
				bg.find('img.front').hide();
			}
			toggleFrontBackLinks("front");
			updateCounter(4, copyList.length);
		}
	});
	$('.features').prepend(frontBack);
	// $('#prevNext .prev').trigger('click');
	return this.each(function(){});
}

/*///////////////////////////

	END - FEATURES SVG

////////////////////////////*/

/*///////////////////////////

	START - GENERAL UTILS

////////////////////////////*/

function roundNumber(number,decimal_points) {
	if(!decimal_points) return Math.round(number);
	if(number == 0) {
		var decimals = "";
		for(var i=0;i<decimal_points;i++) decimals += "0";
		return "0."+decimals;
	}

	var exponent = Math.pow(10,decimal_points);
	var num = Math.round((number * exponent)).toString();
	return num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points)
}

/*///////////////////////////

	END - GENERAL UTILS

////////////////////////////*/
/*///////////////////////////

	END - SIDRALE JS

////////////////////////////*/


