var api_base = 'http://www.mayerfabrics.com/'; // the base url for API calls
var loader = 'http://t3d.mayerfabrics.com/assets/flash/loading.swf'; // the loader swf.  Used only for chair visualization. Animated gif in css used for all other elements
var ease = 'easeInQuad'; // the easing method to use for interface animations
var speed = 500; // the time set for various animations throughout the interfac
var timeout = 10000; // how long to wait before telling the user that the server isn't responding


/**
 * Global variables, used for global (session) data storage/retrieval
*/
var search_string = '';
var page = 1;
var perpage = 8;
var numpages = 1;
var removed = false;

// stuff do when the document is ready
$(document).ready(function(){

	// set some things up
	loadGrades();
	//loadChairs(); // get all the chairs from the server // This was causing some extreme slowness, so I pushed it to happen when the chairs are shown first
	$('form').resetForm(); // reset all the forms
	$('#searchResults .results').empty(); // empty the results div
	
	// remove the excluded types
	if( exclude && exclude.type ){
		for (var i=0;i<exclude.type.length;i++){
			$('#sType option[value="'+exclude.type[i]+'"]').remove();
		}
	}
	
	// Event Bindings
	//////////////////////////////////////////////////////////////////
	
	// search form submit event
	$("form.productSearchForm").ajaxForm({
			beforeSubmit: search
	});
	
	// 'Select New Furniture' Button
	$("#chairs a").click(toggleChairsDisplay);
	
	// New Chair Selection
	$("#chairs div.chair").live('click', function(){
		toggleChairsDisplay();
		loadChair( $(this).find('img').attr('title') );
		return false;
	});
	
	// select a new fabric piece
	$('#searchResults .result').live('click', function(){
		$('#searchResults .result.active').toggleClass('active'); // make currently active selections inactive
		$(this).addClass('active'); // make this active
		loadFabric( $(this).find('img').attr('title'), true ); // load the new fabric
	});
	
	// select a new fabric from the list of related colors
	$("#otherColors .results > div .img img").live('click', function(){
		$('#otherColors .results > div').find('.img.active').removeClass('active');
		$(this).parent().addClass('active');
		loadFabric( $(this).attr('title'), false );
	});
	
	// scroll through related colors
	$('#otherColors span.arrow').click(function(){
		
		var total = $('#otherColors div.results .img').size(); // the total number of related fabrics

		// there's no need to paginate, so stop already
		if(total <= 6){
			$('#otherColors span.arrow').addClass('stop');
			return false;
		}
		
		var max = -((Math.ceil(total/2) * 45) - 135); // the maximum allowed offset
		var pos = parseInt($('#otherColors div.results > div').css('marginTop')); // the current position
		var dir = ($(this).hasClass('up')) ? '+' : '-'; // the direction
		var amnt = (dir == '+' && pos == 0) ? 0 : (dir == '-' && pos <= max) ? 0 : 46; // the new amount
		
		// make the arrows change to 'inactive' when they won't go any farther (and vice versa)		
		if(dir == '+' && pos >= -45){
			$('#otherColors span.arrow.up').addClass('stop');
		}else{
			$('#otherColors span.arrow.up').removeClass('stop');
		}
		
		if( dir == '-' && pos <= max + 45 ){
			$('#otherColors span.arrow.down').addClass('stop');
		}else{
			$('#otherColors span.arrow.down').removeClass('stop');
		}
		
		// finally, do the animation
		$('#otherColors div.results > div').animate({ marginTop : dir+'='+amnt+'px' });		
	});

	// pagination link event: left link
	$(".pagination a.previous").live('click', function(){
		loadPage( page - 1 );
		return false;
	});

	// pagination link event: right link
	$(".pagination a.next").live('click', function(){
		loadPage( page + 1 );
		return false;
	});

	// pagination link events: page numbers
	$(".pagination .pages a").live('click', function(){
		loadPage( parseInt($(this).html()) );
		return false;
	});

	// bind a new window to all anchors with external rel
	$('a[rel="external"]').live('click', function() {
		window.open( $(this).attr('href') );
		return false;
	});
	

	// bind a change of cart href on click
	$('a.order').live('click', function() {
		//addToCart();
		window.open( 'http://mayerfabrics.com/MyAccount.aspx?ViewCart&addcart=M'+fabric+'&v='+vendor, 'mayerfabrics_com' );
		return false;
	});

});		

// Actions
//////////////////////////////////////////////////////////////////

/**
 * hide the initial splash page (actually, remove it from the DOM altogether)
 * @returns null
 */

hideSplash = function(){
	if(!removed){
		$("#app #sType option[value='"+$("#splash #sType option:selected").val()+"']").attr('selected', 'selected');
		$("#app #sColor option[value='"+$("#splash #sColor option:selected").val()+"']").attr('selected', 'selected');
		$("#app #sPattern option[value='"+$("#splash #sPattern option:selected").val()+"']").attr('selected', 'selected');
		$("#app #sPrice option[value='"+$("#splash #sPrice option:selected").val()+"']").attr('selected', 'selected');
		$("#app #mfggrade option[value='"+$("#splash #mfggrade option:selected").val()+"']").attr('selected', 'selected');
		
		$("#app #sNew").attr('checked', $("#splash #sNew:checked").val() );
		$("#app #sKeyword").val( $("#splash #sKeyword").val() );
		
		$('#splash').empty();
		$('#splash').stopTime("timeout").hide(); // stop the timer
	}
}


/**
 * generic function called by form submit actions
 * @returns boolean
 * @param {Array} formData This holds all the data from the form
 * @param {Object} jqForm a jQuery object encapsulating the form element
 * @param {Object} options Options originally sent to ajax form binding
 */
search = function(formData, jqForm, options){
	
	formData.remove(-1); // take out the button
	
	// remove the empty values
	for (i=0;i<formData.length;i++){

		if(formData[i].value == '' || formData[i].value == null){
			formData.remove(i);
		}
	}
	
	formData.push({'name':'mfg', 'value':vendor});
	
	// remove the excluded types
	if( exclude && exclude.type ){
		ex = '';
		for (var i=0;i<exclude.type.length;i++){
			ex += exclude.type[i];
			if(i != exclude.type.length-1) ex += ',';
		}
		
		formData.push({'name':'xType', 'value':ex});
		
	}	
	
	search_string = $.param(formData); // set the global search string val, used by pagination calls
	updateResults( search_string, 1 ); // update the search results to page 1
	updateBreadcrumb( formData ); // set the breadcrumb up
	
	return false;
}

/**
 * function to bind pagination events to updating results
 * @returns null
 * @param {Number} nextPage The new page to progress to
 */
loadPage = function(nextPage){
	nextPage = (nextPage > numpages) ? numpages : (nextPage <= 0) ? 1 : nextPage; // clean the nextpage var
	page = nextPage || page; // the next page is now the current page

	updateResults(search_string, page); // update the results based on the new page
}

/**
 * change up the search results based on the last search preformed and pagination
 * @returns boolean
 * @param {String} params The url string of parameters for the search
 * @param {Number} newPage The number of the new page of results
 */
updateResults = function(params, newPage){
	
	// if it's the first search, let's hide the splash page
	// and set a timer to show a message (if the server takes too long to respond) 
	// the timer is deleted in the hidesplash function
	if(!removed){
		$('#splash > *').hide();

		$('#splash').oneTime(timeout, 'timeout', function() {
			$('<p/>').addClass('timeout').html('The server appears to be experiencing unusually high load.  Please try again in a few minutes.').hide().appendTo('#splash').fadeIn(600);
		});
	}
	
	// get the data from the server
	$.getJSON(api_base+"Search.aspx?"+params+"&format=json&page="+newPage+"&perPage="+perpage+"&callback=?", function(data){
		
		$('#searchResults .results').empty(); // empty the results div
		
		numpages = parseInt(data[0].total_pages); // get the total number of pages
		
		data.remove(0); // take out the first object, which has the pagination data
		
		// if there is no data, tell the user and then stop
		if(data.length == 0){
			numpages = 0;
			$('#searchResults .results').append('<div class="empty">0 Results</div>');
			updatePagination(0);
			return false;
		}
		
		/*
		if(data.length < 8)
			numpages = newPage;
		*/
		// set the global page var
		page = newPage;
		
		// if it's a brand new search, load the first fabric
		if(page == 1)
			loadFabric(data[0].product_number, true);
		
		// append all of the fabrics to the results div
		
		for (i=0;i<data.length;i++){
			var item = data[i];
			var d = new Date(), dts = (d.getFullYear() + '').substr(2,2) + pad(d.getMonth()+1,2) + pad(d.getDate(),2) + pad(d.getHours(),2);
			var result = $('<div/>').addClass('result').html('<div class="img"><img title="'+item.product_number+'" src="http://images.mayerfabrics.com/img?set=key[fabric],value[%27'+item.product_number+'%27]&call=url[file:/webtn]&sink&dts='+dts+' /></div><span class="title">'+item.name.split('(',1)+'</span>');

			//if(item.mfggrade !== '') $('<span/>').addClass('grade').html('Grade '+item.mfggrade).appendTo(result);
			result.appendTo('#searchResults .results');
		}
		
		// update the pagination accordingly
		updatePagination(numpages);
		
    });
	
	return false;
}

/**
 * Update the breadcrumb with new search criteria
 * @returns null
 */
updateBreadcrumb = function(){
	$('#crumb span.type').html( $("#sType option:selected").val() == '' ? '' : $("#sType option:selected").html() );
	$('#crumb span.range').html( $("#sColor option:selected").val() == '' ? '' : $("#sColor option:selected").html() );
	$('#crumb span.pattern').html( $("#sPattern option:selected").val() == '' ? '' : $("#sPattern option:selected").html() );
	$('#crumb span.price').html( $("#sPrice option:selected").val() == '' ? '' : $("#sPrice option:selected").html() );
	$('#crumb span.new').html( $("#sNew:checked").val() == 'true' ? 'New Collections' : '' );
	$('#crumb span.search').html( $("#sKeyword").val() == '' ? '' :'"'+$("#sKeyword").val()+'"' );

	if($("#mfggrade").size() != 0)
		$('#crumb span.grade').html( $("#mfggrade option:selected").val() == '' ? '' : 'Grade ' + $("#mfggrade option:selected").html() );
	
	// jQuery (and Sizzle [and therefore John Resig]) is awesome
	$('#crumb span:not(:empty):not(:last)').append(',');

}

/**
 * update the pagination based on the current page and the new total
 * @returns null
 * @param {Number} the total number of pages
 */
updatePagination = function(total){
	
	numpages = total || numpages; // set the new total if it's set
	
	var loop = (numpages > 9) ? 7 : numpages;
	var start = (numpages < 9) ? 1 : (page <= 3) ? 1 : page - 3;
	var end = (numpages < 9) ? numpages : (page < 4) ? 7 : page + 3;
	end = (end > numpages) ? numpages : end;
	
	if(numpages == 0){
		$('.pagination .wrapper').hide();
	}else{
		$('.pagination .wrapper').show();
	}
	
	var pages = $('.pagination .wrapper .pages');
	
	pages.empty();
	
	
	for(var i=start; i <= end; i++){
		var classes = (page == i) ? 'resultpage active' : 'resultpage';
		pages.append('<a class="'+classes+'" href="#">'+i+'</a>');
	}

	if(page > 4){
		pages.remove('a:first').prepend('<a class="resultpage" href="#">1</a> ... ');
		$('.pagination .wrapper .pages a:not(:first)').after(' <span>|</span> ');
	}else{
		//$('.pagination .wrapper .pages a:first').after(' | ');
		$('.pagination .wrapper .pages a').after(' <span>|</span> ');
	}

	if(page <= numpages - 5 && numpages > 8){
		pages.find(':last-child').remove();
		pages.append('... <a class="resultpage" href="#">'+numpages+'</a>');
	}else{
		pages.find(':last-child').remove();
	}
	
	$('.pagination .wrapper').width( $('.pagination .pages').width() * (1.8) + 80 );
	
	if(numpages == 1){
		pages.empty().append('1');
		$('.pagination .wrapper').width(108);
	}
	
	pages.prepend('Page ');
	
	hideSplash();
}


/**
 * laod the fabric data into the fabric view
 * @returns null
 * @param {String} newFabric The new fabric product number to load
 * @param {Bool} related Whether to load related fabrics
 */
loadFabric = function(newFabric, related){
	
	fabric = newFabric || fabric;

	$('div.patternDetails .img').empty().append('<img src="http://images.mayerfabrics.com/img?set=key[fabric],value[%27'+fabric+'%27]&call=url[file:/BuildSearchView]&sink" />');
	$.getJSON(api_base+"Product.aspx?i="+fabric+"&format=json&mfg="+vendor+"&callback=?", function(data){

		if(related) loadRelated(data[0].colors); // get the related colors
		
		//  update all of the various bits of data into the interface
		$('div.patternDetails span.name').html(data[0].name);
		$('div.patternDetails span.category').html('Category: '+data[0].category);
		$('div.patternDetails span.width').html('Width: '+data[0].width);
		$('div.patternDetails span.content').html('Content: '+data[0].content);
		$('div.patternDetails span.product_number').html(data[0].product_number);
		$('div.patternDetails span.finish').html('Finish: '+data[0].finish);
		$('div.patternDetails span.color').html('Color: '+data[0].color_desc);
		if(data[0].mfggrade && data[0].mfggrade != ''){
			$('div.patternDetails span.grade').html('Grade: '+data[0].mfggrade);
		}else{
			$('div.patternDetails span.grade').html('');
		}
		
		// firefox seems to be automatically escaping things when set to href, so we'll store in DATA and open it onClick
		var chain = encodeURIComponent("set=key[vendor],value['"+vendor+"']&set=key[model],value['"+chair+"']&set=key[fabric],value['"+data[0].product_number+"']&call=url[file:/BuildViz]&scale=width[300]&sink");
		$('div.patternDetails div.right a.pdf').data('href','http://www.mayerfabrics.com/ItemSpecSheet.ashx?Company=01&Warehouse=01&ItemNum='+data[0].product_number+'&ImgChain='+chain)
			.click(function(){
				window.open($(this).data('href'));
				return false;
			});
			
		$('div.patternDetails div.right a.large').attr('href','http://images.mayerfabrics.com/img?set=key[vendor],value[%27'+vendor+'%27]&set=key[model],value[%27'+chair+'%27]&set=key[fabric],value[%27'+data[0].product_number+'%27]&call=url[file:/BuildViz]&sink');
		
		
		$('div.patternDetails span.properties').empty().html('Properties: ');
		
		for( var i=0; i < data[0].properties.length; i++){
			
			if(data[0].properties[i] == 'fire')
				$('div.patternDetails span.properties').append('<img src="http://mayerfabrics.com/images/ActSmallFire.gif" alt="Fire">');

			if(data[0].properties[i] == 'wet dry')
				$('div.patternDetails span.properties').append('<img src="http://mayerfabrics.com/images/ActSmallWetDry.gif" alt="Wet Dry">');
			
			if(data[0].properties[i] == 'light')
				$('div.patternDetails span.properties').append('<img src="http://mayerfabrics.com/images/ActSmallLight.gif" alt="Light">');
		
			if(data[0].properties[i] == 'physical properties')
				$('div.patternDetails span.properties').append('<img src="http://mayerfabrics.com/images/ActSmallPhysicalProperties.gif" alt="Physical Properties">');									
		
		}
		
		if(page == 1)
			$("#searchResults div.result div.img img[title='"+newFabric+"']").closest('div.result').addClass('active');
		
    });			

	loadChair(chair); // load the new chair
	
}


/**
 * Fill the 'related fabrics' area
 * @returns null
 * @param {Array} related The list of related colors
 */
loadRelated = function(related){
	$("#otherColors div.results > div").empty().animate({ marginTop : '0px' });
	
	$.each(related, function(i,item){
		// insert the new images
		var classs = (item == fabric) ? 'img active' : 'img';
		var d = new Date(), dts = (d.getFullYear() + '').substr(2,2) + pad(d.getMonth()+1,2) + pad(d.getDate(),2) + pad(d.getHours(),2);
		$("#otherColors .results > div").append('<div class="'+classs+'"><img title="'+item+'" src="http://images.mayerfabrics.com/img?set=key[fabric],value[%27'+item+'%27]&call=url[file:/webtn]&sink&dts='+dts+'" /></div>');
		
		if(i <= 6){
			$('#otherColors span.arrow').addClass('stop');
		}else{
			$('#otherColors span.arrow').removeClass('stop');
		}
	});
	
	$('#otherColors span.up').addClass('stop');
	
}

/**
 * Load a chair
 * @returns null
 * @param {String} the id of the chair to load
 */
loadChair = function(newchair){

	chair = newchair || chair;
	
	$('#chair .zoom .flash').empty().flash({
		src: "http://www.mayerfabrics.com/resources/SimpleZap-2.1.1-mayer.swf?chain=set%3dkey%5bvendor%5d%2cvalue%5b'"+vendor+"'%5d%26set%3dkey%5bmodel%5d%2cvalue%5b'"+window.chair+"'%5d%26set%3dkey%5bfabric%5d%2cvalue%5b'"+fabric+"'%5d%7ccall%3durl%5bfile%3a%2fBuildViz%5d%7csink&server=images.mayerfabrics.com&uri=img&cacheEnabled=true&controls=always&controlsTransparent=false&maxZoom=1.0&customLogo="+loader,
		width: '373',
		height: '338',
		wmode: "transparent"
	});

	//*** edit added 11/12/10 - NLH to update the "Download Furniture Image" link
	$(".patternDetails .large").attr("href", "http://images.mayerfabrics.com/img?set=key[vendor],value['"+vendor+"']&set=key[model],value['"+window.chair+"']&set=key[fabric],value['"+fabric+"']&call=url[file:/BuildViz]&sink");
}


var chairs_loaded = false;

/**
 * Slide the chair list up and down
 * @returns boolean
 */
toggleChairsDisplay = function(){	
	
	ntop = ($("#chairs a").hasClass('up')) ? '0' : '-345';
	nheight = ($("#chairs a").hasClass('up')) ? '18' : '363';
	//$("#chairs > div").height(nheight+"px");
	$("#chairs > div").animate({marginTop:ntop},speed, ease, function(){
		if(!chairs_loaded) loadChairs();
		$("#chairs a").toggleClass('up');
	});
	return false;
}

/**
 * Load all of the chairs for a manufacturer
 * @returns null
 */
loadChairs = function(){
	$.getJSON(api_base+"json.aspx?req=chairs&mfg="+vendor+"&callback=?", function(data){
	
		//chair = data[0];
		$("#chairs > div > div").empty();
		
		for (var i = data.length-1; i >= 0; i--){			
			var img = $('<img/>').attr('title', data[i]).attr('src',"http://images.mayerfabrics.com/img?source=name[mImage],url[file:/Models/"+vendor+"/"+data[i]+"/"+data[i]+".jpg]&scale=width[125]&sink");
			$('<div/>').addClass('chair').html(img).appendTo("#chairs > div > div");
		}
		
		chairs_loaded = true;

    });
}


/**
 * Load all of the grades for the mfg
 * @returns null
 */
loadGrades = function(){

	$.getJSON(api_base+"json.aspx?req=mfggrades&mfg="+vendor+"&callback=?", function(data){

		for (i=0;i<data.length;i++){		
			$('<option/>').attr('value',data[i]).html(data[i]).appendTo("select[name=mfggrade]");
		}

    });
}


/**
 * remotely adds selected fabric to cart
 * @returns null
 */
addToCart = function(){
	
	showModal('Adding ' + $('div.patternDetails .name').html() +' to your cart.', 'wait');
	
	$.getJSON(api_base+"json.aspx?req=addcart&i="+fabric+"&callback=?", function(data){
			
    });
		
}

showModal = function(msg, type){
	var classs = (type == 'hold') ? 'wait' : 'complete';
	$('#modal').addClass(classs).html('<p>'+msg+'</p>').fadeIn();
}

hideModal = function(){
	$('#modal').fadeOut();
}


/**
 * extend the array object with a remove method
 * @returns Number length of the string
 * @param {Number} from the beginning value
 * @param {Number} to the end value
 * @author John Resig: http://ejohn.org/blog/javascript-array-remove/
 */
Array.prototype.remove = function(from, to){
  this.splice(from,
    !to ||
    1 + to - from + (!(to < 0 ^ from >= 0) && (to < 0 || -1) * this.length));
  return this.length;
};

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}
