Array.prototype.max = function(){
    return Math.max.apply( Math, this );
};

YAS = {};

$(document).ready(function(){
	Cufon.replace('h2', { fontFamily: 'Gill Sans' });
	Cufon.replace('h2 strong', { fontFamily: 'Gill Sans Strong', color: '#f3b42e' });
	Cufon.replace('#news h2', { fontFamily: 'Gill Sans Strong', color: '#f3b42e' });
	Cufon.replace('h1', { fontFamily: 'Gill Sans Strong' });
	Cufon.replace('h1 strong', { fontFamily: 'Gill Sans', color: '#f3b42e' });
	Cufon.replace('.category-list-product h2', { fontFamily: 'Gill Sans Strong', color: '#f3b42e' });


	var html  = '<div class="wrap">';
		html += '<form id="locatorform"><label for="locatorpostalcode">Please enter your Postal Code:</label><input type="text" id="locatorpostalcode" name="locatorpostalcode" value=""></form>';
		html += '<div id="locatorloading"></div>';
		// html += '<div id="locatornumresults"></div>';
		html += '<div id="locatorresults"><ol></ol></div>';
		// html += '<div id="becomeadealer"><a href="/contact/>Contact us today</div> to become a dealer!</div>';
		html += '</div>';
	var locator = $('<div></div>').attr('id','locator').addClass('grid_10').html(html);

	$('#nav-dealerlocator').append(locator);
	$('#locator, #locator *').live('mouseenter mouseleave',function(){
		$('#nav-dealerlocator a').toggleClass('hover');
	});
	
	$('#nav-dealerlocator, #locator *, #locator, #locator .wrap, #locator .wrap *,#locatorform, #locatorform *, #locatorresults, #locatorresults *').live('mouseenter', function(){
		$('#locator').addClass('toggledShow');
	});
	
	$('#nav-dealerlocator, #locator, #locator *, #locator .wrap, #locatorform, #locatorresults').live('mouseleave', function(){
			$('#locator').removeClass('toggledShow');
	});
		
	var geocoder = new GClientGeocoder();
	$('#locatorpostalcode').live('keyup',function(){
		var matches = $(this).val().match(/\w/g);
	    if(matches != null && matches.length == 6) {
			$('#locatorloading').show();
			
			geocoder.getLocations($('#locatorpostalcode').val()+' Canada', function(response){

				if(response.Status.code == 200) {

					var api_url = MYYASTECH_URL+'dealers/nearest/'+MYYASTECH_APIKEY+'/' 
									+ response.Placemark[0].Point.coordinates[1] + '/' 
									+ response.Placemark[0].Point.coordinates[0] + '/callback=?';

					$.getJSON(api_url,function(data){
						$('#locatorresults ol li').remove();
						// $('#locatornumresults').text(data.result.length + ' dealers found near you!');						
						
						$.each(data.result, function(i, val) {
							
							var name = $('<span></span>').addClass('name').html('<strong>' + val.name + '</strong><br />' + val.phone);
							var address = $('<span></span>').addClass('address').html(val.address + '<br />' + val.city + ', ' + val.province);
							
							// show only 3
							if(i < 3) {
								var li = $('<li></li>').append(name, address, $('<div class="clear"></div>'));
							}
							$('#locatorresults ol').append(li);
						});
						$('#locatorloading').hide();
						
					});
				}
			});

		} else {
			$('#locatorresults ul li').remove();
			$('#locatornumresults').text('');
			$('#locatorloading').hide();
		}
		
	});
	
	if($('#product-tabs').length > 0) {
		$('#product-tabs').tabs({
			show: function(event, ui){
				if(ui.index == 1) { //1 == photos
					var heights = [];
					$('#photos li').each(function(){
						heights.push($(this).height());
					});
					$('#photos li').height(heights.max());
				}
				
			}
		});
	}
	
	if($('.product-photos li a').length > 0) {
		$('.product-photos li a').lightBox();
	}
	
	if($('#categories').length > 0) {

		YAS.categories = function() {
			return {

				formatData: function() {
					var data = YAS.categories.data;
					var prefix = '';
					var level = 0;

					var parse_object = function(d) {
						$.each(d,function(i,obj){					
							var before = '';
							var after = '';

							if(level !== 0) {
								before 	+= '<span class="childcategory child-'+level+'">';
								after 	+= '</span>';
							}

							level++;

							obj.name = before + obj.name + after;

							YAS.categories.table.addRow(obj);

							if(obj.categories !== undefined && obj.categories.length !== 0) {
								parse_object(obj.categories);
							} else {
								level = 0;
							}
						});
					}

					parse_object(data.result);
				},

				columnDefs: function() {


					this.formatTitle = function(elLiner, oRecord, oColumn, oData) {
						$(elLiner).html('<a class="category-name" href="#" rel="'+oRecord.getData('hash')+'">'+oRecord.getData('name')+'</a> ');
					}

				 	return [
						{key:"name", label:"Name", formatter: this.formatTitle}
					];
				}(),

				loadTable: function(data) {
					this.data = data;
					YAS.categories.data = data;
					// Empty the data so we can work with it AFTER the table has loaded
					data = {result:[]};

					this.ds = new YAHOO.util.DataSource(data.result);
			        this.ds.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
			        this.ds.responseSchema = {
			            fields: ["id","name"]
			        };

			        YAS.categories.table = new YAHOO.widget.DataTable("categories", this.columnDefs, this.ds);

					YAS.categories.table.subscribe("initEvent", this.formatData);
				}
			}
		}();
		
		YAS.files = function() {
			return {

				columnDefs: function() {

					this.formatAction = function(elLiner, oRecord, oColumn, oData) {
						var h = '<a href="http://www.myyastech.ca/api/files/download/'+oRecord.getData('hash')+'" class="download">Download</a> ';

						$(elLiner).html(h);
					};

					this.formatDate =  function(elLiner, oRecord, oColumn, oData) {
						var d = oData;
						d = d.split(' ');
						$(elLiner).html(d[0]);
					}
				 	return [
						{key:"title", label:"Title", formatter: this.formatName},
						{key: 'action', label:'', formatter: this.formatAction}
					];
				}(),

				loadTable: function(data) {
					this.data = data;
					YAS.files.data = data;
					// data = {result:[]}
					this.ds = new YAHOO.util.DataSource(data.result);
			        this.ds.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
			        this.ds.responseSchema = {
			            fields: ["id","title","hash"]
			        };

			        YAS.files.table = new YAHOO.widget.DataTable("files", this.columnDefs, this.ds);
				}
			}
		}();
		
		$.getJSON('http://www.myyastech.ca/api/files/categories/'+MYYASTECH_APIKEY+'/'+DEALER+'/callback=?',function(data){
			YAS.categories.loadTable(data);
		});
		
		$('.category-name').live('click',function(){
			$('.current').removeClass('current');
			$(this).addClass('current');
			
			$.getJSON('http://www.myyastech.ca/api/files/all/'+MYYASTECH_APIKEY+'/'+$(this).attr('rel')+'/callback=?', function(data){
				YAS.files.loadTable(data);
			});
			
			return false;
		});
		
	} 
	
	// Ensures the background image is 100% high
	
	if($('body > div:first-child').height() < ($(document).height()-50)) {
		$('body > div:first-child').height(($(document).height()-50));
	}
	
	if($('#contactform').length > 0) {
		$('#contactform').validate();
	}
});
