var $wrapper = $('#wrapper'),currentHash = null,shapeData = null,swatchData = null,colorData = null,camberData = null,tailData = null,flexData = null;
var paypal = 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=B2CVKZQU7NASS';

var camberString = [];
camberString['camberOne'] = 'Traditional camber 4-5mm';
camberString['camberTwo'] = 'Early-rise 8mm over 25cm<br />Low camber 4-5mm';
camberString['camberThree'] = 'Early-rise 8mm over 25cm<br />No Camber<br />Early-rise 8mm over 25cm';

var tailString = [];
tailString['tailOne'] = 'Full twin tip tail';
tailString['tailTwo'] = 'Half height tail with flat spot';

var flexString = [];
flexString['flexStandard'] = 'Standard';
flexString['flexAggresive'] = 'Aggresive';

jQuery(
	function ($) {
		init();
		bindEvents();
		function init(){
	   		$body = $('html,body').attr('scrollTop',0);
	   		preLoad();
	   	}
	
	   	function preLoad(){
	   		$wrapper.css({height:0,overflow:'hidden'});
			//build everything we need
	     	$(window).bind('load',doLoad);
			//$(window).bind('resize',doResize);
	   	}
	
		function doLoad(e){
			new Swatches().load();
			new Shape().load();
			processHash(location.hash.slice(1));
			$wrapper.css({height:'auto',overflow:'auto'})
			//hide the pre-loader
			$('#preloader').css({display:'none'});
		}
		
		function bindEvents(){
			$('.shapeLnk').live('click',adjustClick);
			$('.sizeLnk').live('click',adjustClick);
			$('.designLnk').live('click',designClick);
			
			
			//camber
			$('.camber').bind('mouseenter',highlight);
			$('.camber').bind('mouseleave',function() {
				if(camberData != $(this).attr('id')) {
					$(this).css({'background-position' : '0 0', 'color' : '#666'});
				}
			});
			$('.camber').bind('click',function() {
				camberData = $(this).attr('id');
				$('.camber').css({'background-position' : '0 0', 'color' : '#666'});
				$(this).mouseenter();
				$(this).parent().children('input').attr('checked','checked');
				//update sidebar
				$('.camberName').html('Camber/Early-Rise<br /><span class="camberOptions">'+camberString[camberData]+'</span>');
			});
			
			//tail
			$('.tail').bind('mouseenter',highlight);
			$('.tail').bind('mouseleave',function() {
				if(tailData != $(this).attr('id')) {
					$(this).css({'background-position' : '0 0', 'color' : '#666'});
				}
			});
			$('.tail').bind('click',function() {
				tailData = $(this).attr('id');
				$('.tail').css({'background-position' : '0 0', 'color' : '#666'});
				$(this).mouseenter();
				$(this).parent().children('input').attr('checked','checked');
				//update sidebar
				$('.tailName').html('Tail Profile<br /><span class="tailOptions">'+tailString[tailData]+'</span>');
				//update build
				if(tailData == 'tailTwo') {
					$('#build').height('526px');
				} else {
					$('#build').height('600px');
				}
			});
			
			//flex
			$('.flex-info').bind('mouseenter',highlight);
			$('.flex-info').bind('mouseleave',function() {
				if(flexData != $(this).attr('name')) {
					$(this).css({'color' : '#666'});
				}
			});
			$('.flex-info').bind('click',function() {
				flexData = $(this).attr('name');
				$('.flex-info').css({'background-position' : '0 0', 'color' : '#666'});
				$(this).mouseenter();
				$('input#'+$(this).attr('name')).attr('checked','checked');
				//update sidebar
				$('.flexName').html('Flex and Stiffness Profile<br /><span class="flexOptions">'+flexString[flexData]+'</span>');
			});
			$('#flexStandard').bind('click',function(){
				var flexID = $(this).attr('id');
				$('div [name='+flexID+']').click();
			});
			$('#flexAggresive').bind('click',function(){
				var flexID = $(this).attr('id');
				$('div [name='+flexID+']').click();
			});
			
			$('.blurIt').bind('blur',fieldBlur);
			$('.blurIt').bind('focus',fieldFocus);
			$('.submitForm').bind('click',submitForm);
		}
		
		function submitForm(){
			new Order().doSubmit();
			return false;
		}
		
		function adjustClick(){
			processHash(this.hash.slice(1));
			return false;
		}
		
		function designClick(){
			var design = this.hash.slice(1);
			colorData = 1;
			newHash = currentHash[0]+','+currentHash[1]+','+design;
			processHash(newHash);
			return false;
		}
		
		//process incoming hash string
		function processHash(locationHash){
			if(locationHash!='') {
				currentHash = locationHash.split(",");
				new Shape().adjust();
			}
		}
		
		function highlight(){
			var linkHeight = $(this).height();
			$(this).css({'background-position' : '0 -'+linkHeight+'px','color' : '#fff'});
		}
	}
);

function Shape(){

	init();
	
	function init(){
		if(!currentHash){
			currentHash = ["0","0","0"];
		}
	}

	this.load = function(){
		$.ajax({
	   		type: "POST",
	   		url: '/ski/json/data',
			dataType: 'html',
	   		success: loadSuccess,
			error: loadError,
			beforeSend: loadBeforeSend,
			complete: loadComplete 
	 	});	
	}
	
	function loadSuccess(data){
		shapeData = eval( "(" + data + ")" );
		makeShapeList();
		doAdjust();
	}
	
	function makeShapeList(){

		var skiItem = '';
		for (_ski in shapeData) {
			skiItem += '<li><div class="shapeContainer">';
			for (_category in shapeData[_ski].categories) {
				skiItem += '<div class="'+shapeData[_ski].categories[_category].identifier+'"></div>';
			}
			skiItem += '</div><a class="shapeLnk" id="shapeItem'+_ski+'" href="#'+_ski+',0,0">'+shapeData[_ski].name+'</a></li>';
		}
		
		$('#shapeList ul').html(skiItem);	
	}
	
	function loadError(data){
		alert('Sorry we couldn\'t find any ski info.   We most likely are having a technical problem.');
	}
	
	function loadBeforeSend(data){
		
	}
	
	function loadComplete(data){
		
	}
	
	this.adjust = function(){
		doAdjust();
	}
	
	function doAdjust(){
		//clear current state for shape list
		$('#shapeList a').removeClass('current');
		//set current shape list
		$('#shapeList #shapeItem'+currentHash[0]).addClass('current');
		//do sizes
		sizeItem = '';
		for (_size in shapeData[currentHash[0]].sizes){
			var cssClass = 'size';
			if(shapeData[currentHash[0]].sizes[_size].length != '') {
				if(currentHash[1] == _size) {cssClass = 'sizeOn';}
				sizeItem += '<a href="#'+currentHash[0]+','+_size+','+currentHash[2]+'" class="sizeLnk '+cssClass+'">';
				sizeItem += shapeData[currentHash[0]].sizes[_size].length+'cm '+shapeData[currentHash[0]].sizes[_size].tip+'.'+shapeData[currentHash[0]].sizes[_size].waist+'.'+shapeData[currentHash[0]].sizes[_size].tail+'</a><br />';
			}
		}
		$('span.sizes').html(sizeItem);
		//description
		$('div.description').html(shapeData[currentHash[0]].description);
		//make the description list pretty
		$('div.description ul li').prepend('<span class="highlight">+</span> ');
		//deposit
		if(shapeData[currentHash[0]].deposit_price == '0'){
			$('span.price').html('Unavailable');
		} else {
			$('span.price').html('$'+shapeData[currentHash[0]].deposit_price+' Deposit');
		}
		//completion price
		if(shapeData[currentHash[0]].semi_price == '0'){
			$('span.sale').html(' ');
		} else {
			$('span.sale').html('$'+shapeData[currentHash[0]].semi_price+' Upon Completion');
		}
		//swap image
		var swatch = currentHash[2];
		var imageName = shapeData[currentHash[0]].name.replace(/[^a-zA-Z0-9]+/g, "").toLowerCase();
		
		if(currentHash[2] == '0'){
			swatch = '666';
		}
		$('#shapeBuilder #build').css({background:'transparent url("/skis/fulls/'+imageName+'.'+swatch+'.png") no-repeat 102px 0'});
		
		//set swatch name
		if(swatch != '666'){
			var swatchNameReadable = '';
			var swatchName = swatch.replace(/_+/g, " ");
			swatchName = swatchName.split(' ');
        	for(var c=0; c < swatchName.length; c++) {
        		swatchNameReadable += swatchName[c].substring(0,1).toUpperCase() + swatchName[c].substring(1,swatchName[c].length) + ' ';
        	}
			$('.swatchName').text(swatchNameReadable);
		} else {
			$('.swatchName').text('');
		}
		
		//shape size
		var shapeSize = shapeData[currentHash[0]].sizes[currentHash[1]].length+'cm '+shapeData[currentHash[0]].sizes[currentHash[1]].tip+'.'+shapeData[currentHash[0]].sizes[currentHash[1]].waist+
		'.'+shapeData[currentHash[0]].sizes[currentHash[1]].tail+'<br />Radius: '+
		shapeData[currentHash[0]].sizes[currentHash[1]].turn_radius+'m<br />Effective Edge: '+
		shapeData[currentHash[0]].sizes[currentHash[1]].effective_edge+'mm';

		$('.shapeSize').html(shapeSize);
		
		$('#tip').text(shapeData[currentHash[0]].sizes[currentHash[1]].tip);
		$('#waist').text(shapeData[currentHash[0]].sizes[currentHash[1]].waist);
		$('#tail').text(shapeData[currentHash[0]].sizes[currentHash[1]].tail);
		$('#length').text(shapeData[currentHash[0]].sizes[currentHash[1]].length+'cm');
		$('#effective_edge').text(shapeData[currentHash[0]].sizes[currentHash[1]].effective_edge);
		$('#turn_radius').text(shapeData[currentHash[0]].sizes[currentHash[1]].turn_radius);
		
		//shape name
		$('.shapeName').text(shapeData[currentHash[0]].name);
		
		//hide camber if gambit
		if(shapeData[currentHash[0]].name == 'Gambit') {
			$('ul#camber').hide();
			camberData = "Gambit";
			$('.camberName').html('Camber/Early-Rise<br /><span class="camberOptions">Gambit unique profile.<br /><a href="/skins/default/GambitRockerProfileFullBoth.pdf">Click to download</a></span>');
		} else {
			$('ul#camber').show();
			camberData = null;
			$('.camberName').html(' ');
		}
		
		
		var ski_data = shapeData[currentHash[0]].name + ' | ' +shapeSize+ ' | '+swatchNameReadable;
		$('#ski_data').val(ski_data);
		
		
		
	}
}

function Swatches(){

	init();
	
	function init(){

	}

	this.load = function(){
		$.ajax({
	   		type: "POST",
	   		url: '/ski/json/swatches',
			dataType: 'html',
	   		success: loadSuccess,
			error: loadError,
			beforeSend: loadBeforeSend,
			complete: loadComplete 
	 	});	
	}
	
	function loadSuccess(data){
		swatchData = eval( "(" + data + ")" );
		makeSwatchList();
	}
	
	function makeSwatchList(){
		for (_swatchCat in swatchData) {
			var swatchItem = '';
			for (_swatch in swatchData[_swatchCat]) {
				
				var swatchId = swatchData[_swatchCat][_swatch].replace('.png', '').toLowerCase();

				var swatchNameReadable = '';
				var swatchName = swatchData[_swatchCat][_swatch].replace(/_+/g, " ");
				swatchName = swatchName.split(' ');
		        for(var c=0; c < swatchName.length; c++) {
		        	swatchNameReadable += swatchName[c].substring(0,1).toUpperCase() + swatchName[c].substring(1,swatchName[c].length) + ' ';
		        }
		        swatchNameReadable = swatchNameReadable.replace('.png', '');
				swatchItem += '<li><a class="designLnk" href="#'+swatchId+'"><img src="/skis/thumbnails/'+_swatchCat+'/'+swatchData[_swatchCat][_swatch]+'" width="112" height="60" alt="'+swatchNameReadable+'"><br />'+swatchNameReadable+'</a></li>';
				
			}
			
			$('#'+_swatchCat+'Swatches').html(swatchItem);
		}
	}
	
	function loadError(data){
		alert('Sorry we couldn\'t find any ski info.   We most likely are having a technical problem.');
	}
	
	function loadBeforeSend(data){
		
	}
	
	function loadComplete(data){
		
	}
}

function Order(){
	
	this.doSubmit = function(){
	
		if(valid()) {
			var formData = $('#questionForm').serialize();

			$.ajax({
	   			type: "POST",
	   			url: '/order/json/semi',
	   			data: formData,
				dataType: "html",
	   			success: loadSuccess,
	   			error: loadError,
				beforeSend: loadBeforeSend,
				complete: loadComplete 
	 		});	
		}
	}
	
	function valid(){
		var errorMsg = '';
		if(colorData == null){errorMsg += "Please Choose Color\n";}
		if(camberData == null){errorMsg += "Please Choose Camber / Early-Rise Options\n";}
		if(tailData == null){errorMsg += "Please Choose Tail Profile\n";}
		if(flexData == null){errorMsg += "Please Choose Flex / Stiffness Profile\n";}
		if($('#full_name').val() == '' || ($('#full_name').attr('title') == $('#full_name').val())){errorMsg += "Please enter your full name\n";}
		if($('#phone').val() == '' || ($('#phone').attr('title') == $('#phone').val())){errorMsg += "Please enter your phone\n";}
		if($('#email').val() == '' || ($('#email').attr('title') == $('#email').val())){errorMsg += "Please enter your email\n";}	
		
		if(errorMsg != ''){
			alert(errorMsg);
			return false;
		}else{
			return true;
		}
	}
	
	function loadSuccess(data){
		processResponse = eval( "(" + data + ")" );
		$('.thanksMsg').show();
		$('.requestArea').hide();
	}	
	
	function loadError(data){
		alert('Sorry we couldn\'t submit your form data right now.');
	}
	
	function loadBeforeSend(data){
		
	}
	
	function loadComplete(data){
		window.location = paypal;
	}
}


//some global methods
function fieldFocus(e){
    if ($(this).val() == $(this)[0].title)
    {
        $(this).val("");
    }
}

function fieldBlur(e){
    if ($(this).val() == "")
    {
        $(this).val($(this)[0].title);
    } else {
    	$('.userDetails').show();
    	var appendStr = '';
    	if($(this)[0].id == 'city') {
    		appendStr = ', ';
    	}
    	$('.'+$(this)[0].id).text($(this).val()+appendStr);
    }
}






