var $wrapper = $('#wrapper'),currentHash = null,shapeData = null,swatchData = null;
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);
			$('.blurIt').bind('blur',fieldBlur);
			$('.blurIt').bind('focus',fieldFocus);
			$('.submitForm').bind('click',submitForm);
			$('.tip_choice').bind('mouseenter',function(){
				$(this).addClass('active');
			});
			$('.tip_choice').bind('mouseleave',function(){
				$(this).removeClass('active');
			});
			$('#tip_traditional').bind('click',function(){
				$('#tip_tapered').removeClass('selected');
				$(this).addClass('selected');
				$(this).find('input').attr("checked", "checked");
				$('.tipName').html('Traditional Tip');
			});
			$('#tip_tapered').bind('click',function(){
				$('#tip_traditional').removeClass('selected');
				$(this).addClass('selected');
				$(this).find('input').attr("checked", "checked");
				$('.tipName').html('Early Tapered Tip');
			});
		}
		
		function submitForm(){
			new Order().doSubmit();
			return false;
		}
		
		function adjustClick(){
			processHash(this.hash.slice(1));
			return false;
		}
		
		function designClick(){
			var design = this.hash.slice(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 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> ');
		//price
		$('span.price').html('$'+shapeData[currentHash[0]].price);
		//sale price
		if(shapeData[currentHash[0]].sale_price != '0'){
			$('span.sale').html('Sale - $'+shapeData[currentHash[0]].sale_price);
		} else {
			$('span.sale').html('');
		}
		//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);
		
		
		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/process',
	   			data: formData,
				dataType: "html",
	   			success: loadSuccess,
	   			error: loadError,
				beforeSend: loadBeforeSend,
				complete: loadComplete 
	 		});	
		}
	}
	
	function valid(){
		var errorMsg = '';
		if(!$('#tip_traditional_input').is(':checked') && !$('#tip_tapered_input').is(':checked')){errorMsg += "Please choose a tip style\n";}
		if($('#full_name').val() == '' || ($('#full_name').attr('title') == $('#full_name').val())){errorMsg += "Please enter your full name\n";}
		if($('#street_address').val() == '' || ($('#street_address').attr('title') == $('#street_address').val())){errorMsg += "Please enter your street address\n";}
		if($('#city').val() == '' || ($('#city').attr('title') == $('#city').val())){errorMsg += "Please enter your city\n";}
		if($('#state').val() == '' || ($('#state').attr('title') == $('#state').val())){errorMsg += "Please enter your state\n";}
		if($('#zip_code').val() == '' || ($('#zip_code').attr('title') == $('#zip_code').val())){errorMsg += "Please enter your zip code\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($('#weight').val() == '' || ($('#weight').attr('title') == $('#weight').val())){errorMsg += "Please enter your weight\n";}
		if($('#height').val() == '' || ($('#height').attr('title') == $('#height').val())){errorMsg += "Please enter your height\n";}
		if($('#age').val() == '' || ($('#age').attr('title') == $('#age').val())){errorMsg += "Please enter your age\n";}
		if($('#gender').val() == '' || ($('#gender').attr('title') == $('#gender').val())){errorMsg += "Please enter your gender\n";}
	
		
		if(errorMsg != ''){
			alert(errorMsg);
			return false;
		}else{
			return true;
		}
	}
	
	function loadSuccess(data){
		processResponse = eval( "(" + data + ")" );
		//console.debug(processResponse);
		$('.thanksMsg').show();
		$('.requestArea').hide();
	}	
	
	function loadError(data){
		alert('Sorry we couldn\'t submit your form data right now.');
	}
	
	function loadBeforeSend(data){
		
	}
	
	function loadComplete(data){
		
	}
}


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






