$(function(){
	var first = 0;
	var speed = 1000;
	var pause = 8000;
	
	function tickerRemoveFirst(){
		var first = '<li class="'+$('#ticker ul li:first').attr('class')+'">'+$('#ticker ul li:first').html()+'</li>';
		$('#ticker ul li:first').animate({backgroundPosition:'-60px 100%',opacity:0},'fast').slideUp(speed, function() {$(this).remove();});
		tickerAddLast(first);
	}
	function tickerAddLast(first){
		var last = first;
		$('#ticker ul').append(last);
		$('#ticker ul li:last').css({backgroundPosition:'0 100%',opacity:1}).show();
	}
	
	if ($('#ticker ul li').length>0) interval = setInterval(tickerRemoveFirst, pause);
	
	$('#show_home_slide').hover( function(){ $('#hero_header img').animate({top:'0'},'fast').clearQueue(); },
								 function(){ $('#hero_header img').animate({top:'-102px'},'fast').clearQueue(); });
	
	$('#show_cafe_slide').hover( function(){ $('#hero_header img').animate({top:'-204px'},'fast').clearQueue(); },
								 function(){ $('#hero_header img').animate({top:'-102px'},'fast').clearQueue(); });
	
	$('#aside #unit_offer_glimpse a').hover(function(){
												$(this).find('img').animate({top:'-50px'});
												$(this).find('div').animate({top:'102px'});
											},
											function(){
												$(this).find('img').animate({top:'0'});
												$(this).find('div').animate({top:'224px'});
											});
	
	// To detect native support for the HTML5 placeholder attribute
	var fakeInput = document.createElement("input"),
		placeHolderSupport = ("placeholder" in fakeInput);

	// Applies placeholder attribute behavior in web browsers that don't support it
	if (!placeHolderSupport) {
		var searchField = $("#updates_email"),
			originalText = searchField.attr("placeholder");

		searchField.val(originalText);
		searchField.addClass("placeholder");
		searchField.bind("focus", function () {
			searchField.removeClass("placeholder");
			if (searchField.val() === originalText) {
				searchField.val("");
			}
		});

		searchField.bind("blur", function () {
			if (searchField.val().length === 0) {
				searchField.val(originalText);
				searchField.addClass("placeholder");
			}
		});
	}
	
	$.fn.removeErrorMessage = function() {
		$('#err_'+this.attr('id')).remove();
		this.removeClass('error');
	}
	
	//Adds Inline Error Message
	$.fn.addErrorMessage = function(msg,target) {
		msg = msg?msg:'You must complete this';
		this.addClass('error');
		$('#' + target).after('<div class="error-message" id="err_'+this.attr('id')+'">'+msg+'</div>');
	}

	//Checks if textfield is blank
		$.fn.validateNotBlank = function(msg,target) {
		msg = msg?msg:'This cannot be left blank';
		if($.trim(this.val())=='') {
			if (!$('#err_'+this.attr('id')).length>0) {
				this.addErrorMessage(msg,target);
			} return false; // Fail
		} else this.removeErrorMessage();
		return true;
	}
	
	$.fn.urbanSelect = function(settings) {

         /* default settings */
         var config = {'price_id': 'product_price'};
         if (settings) {
             $.extend(config, settings);
         }

		function ucfirst (str) {
		    // Makes a string's first character uppercase  
		    // 
		    // version: 1008.1718
		    // discuss at: http://phpjs.org/functions/ucfirst
		    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +   bugfixed by: Onno Marsman
		    // +   improved by: Brett Zamir (http://brett-zamir.me)
		    // *     example 1: ucfirst('kevin van zonneveld');
		    // *     returns 1: 'Kevin van zonneveld'
		    str += '';
		    var f = str.charAt(0).toUpperCase();
		    return f + str.substr(1);
		}
		
		function strtolower (str) {
		    // Makes a string lowercase  
		    // 
		    // version: 1008.1718
		    // discuss at: http://phpjs.org/functions/strtolower
		    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		    // +   improved by: Onno Marsman
		    // *     example 1: strtolower('Kevin van Zonneveld');
		    // *     returns 1: 'kevin van zonneveld'
		    return (str+'').toLowerCase();
		}
		
		/* change the selected item and price based on the radios */
		function changeSelectAndPrice(select) {
			var sku_values = $(select).val().split('-');
			var sku = sku_values[0];
			
			// first part = SKU
			// second part = PRICE
			// third part = WEIGHT
			// fourth part = TYPE
			
			// what we need to do, is work out the price based on the SKU, WEIGHT and TYPE
			var weight = $('input[name=weight_radio]:checked').val();
			var type = $('input[name=type_radio]:checked').val();
			var price = getPriceFromSkuWeightType(sku, weight, type, select);
			var new_select_value = sku+'-'+price+'-'+weight+'-'+type;
			$(select).val(new_select_value);
			$('#'+config.price_id).text('£'+(parseFloat(price)/100).toFixed(2));
		}
		
		function getPriceFromSkuWeightType(sku, weight, type, select) {
			// given the sku, weight and type get the price
			// do it by searching through the options in the select until one matches
			var options = $(select).children('option');
			for(i=0; i<options.length; i++) {
				var value = $(options[i]).val();
				var split_values = value.split('-');
				var current_sku = split_values[0];
				var current_type = split_values[3];
				var current_weight = split_values[2];
				var current_price = split_values[1];
				if(sku == current_sku && weight == current_weight && type == current_type) return current_price;
			}
		}
		
		function parseType(type) {
			return ucfirst(strtolower(type));
		}
		
		function parseWeight(weight) {
			return strtolower(weight+'g');
		}

         /* enable urbanSelect for each element */
         this.each(function() {
			
			var types = {};
			var weights = {};
			
			var options = $(this).children('option');
			for(i=0; i<options.length; i++) {
				// console.log($(options[i]).val());
				var value = $(options[i]).val();
				var split_values = value.split('-');
				var type = split_values[3];
				var weight = split_values[2];
				types[type] = ucfirst(strtolower(type));
				weights[weight] = weight;
			}
			
			var typeFieldset = $(document.createElement('fieldset')).addClass('radios').attr('id','product_type_radios');
			var typeH3 = $(document.createElement('h3')).text('Type');
			typeFieldset.append(typeH3);
			var first = true;
			for(type in types) {
		        var typeDiv = $(document.createElement('div')).addClass('field');
				var typeLabel = $(document.createElement('label')).attr('for', 'type_radio_'+strtolower(type)).text(parseType(type));
				var typeRadio = $(document.createElement('input')).attr('id', 'type_radio_'+strtolower(type)).attr('type', 'radio').val(type).attr('name', 'type_radio');
				if(first) typeRadio.attr('checked', 'checked');
				typeDiv.append(typeRadio).append(typeLabel);
				typeFieldset.append(typeDiv);
				first = false;
			}
			typeFieldset.append(typeDiv);
			
			var weightFieldset = $(document.createElement('fieldset')).addClass('radios').attr('id','product_weight_radios');
			var weightH3 = $(document.createElement('h3')).text('Weight');
			weightFieldset.append(weightH3);
			first = true;
			for(weight in weights) {
			    var weightDiv = $(document.createElement('div')).addClass('field');
				var weightLabel = $(document.createElement('label')).attr('for', 'weight_radio_'+strtolower(weight)).text(parseWeight(weight));
				var weightRadio = $(document.createElement('input')).attr('id', 'weight_radio_'+strtolower(weight)).attr('type', 'radio').val(weight).attr('name', 'weight_radio');
				if(first) weightRadio.attr('checked', 'checked');
				weightDiv.append(weightRadio).append(weightLabel);
				weightFieldset.append(weightDiv);
				first = false;
			}
			weightFieldset.append(weightDiv);
			
			var select = this;
			$(weightFieldset.find('input')).change(function(){
				changeSelectAndPrice(select);
			});
			
			$(typeFieldset.find('input')).change(function(){
				changeSelectAndPrice(select);
			});
			
			$(this).parents('fieldset').after(weightFieldset).after(typeFieldset);
			
         });

        return this;
    };
    
    var ie = (function(){

        var undef,
            v = 3,
            div = document.createElement('div'),
            all = div.getElementsByTagName('i');

        while (
            div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );

        return v > 4 ? v : undef;

    }());
    
    // Don't use radio buttons if less than IE8 due to a bug with createElement and the name attribute
    if(ie<8) $('#product_select').show();
	else $('select#product_code').urbanSelect();

});

