var sendContactForm = function(el) {
	var form = $('contactform');
	
	var data = form.serialize(true);
	
	Object.extend(data,{
		action: 'contactform'
	});
	
	new Ajax.Request('/', {
		method: 'post',
		parameters: data,
		onSuccess: function(t) {
			if (t.responseText == 'success') {
				form.select('.confirmation')[0].appear();
				form.select('.fields')[0].hide();
			} else {
				alert(t.responseText);
			}
		}
	});
};
var swipe = function(btn,wrap,direction) {
	direction = direction*-1;
	
	var marginLeft = parseInt(wrap.getStyle('marginLeft').match(/-?(\d+)/ig)[0]);
	var width = parseInt(wrap.getStyle('width').match(/-?(\d+)/ig)[0]);
	
	var newMargin = marginLeft + (100*direction);
	newMargin = Math.round(newMargin/100)*100;
	var stop = false; 
	if (Math.abs(newMargin) >= width) {
		stop = true;
	} else if (newMargin > 0) {
		stop = true;
	}
	if (stop) {
		return;
	}
	
	new Effect.Tween(null, marginLeft, newMargin,{duration:0.4, afterFinish: function(){
		productSlideBtns(wrap)
		productFilter.page = (Math.abs(newMargin)/100);
		document.location.hash = '#!/productlist:' + productFilter.category + ';' + productFilter.meta + ';' + productFilter.text + ';' + productFilter.page;
		$('productslidewrap').fire('products:slide');
	}}, function(m){
		wrap.setStyle({marginLeft: m + '%'});
	});
};
var productSlideBtns = function(wrap) {
	var marginLeft = parseInt(wrap.getStyle('marginLeft').match(/-?(\d+)/ig)[0]);
	var width = parseInt(wrap.getStyle('width').match(/-?(\d+)/ig)[0]);
	
	var left  = $$('.leftright .left a')[0];
	var right = $$('.leftright .right a')[0];
	var leftImg = left.select('img')[0];
	var rightImg = right.select('img')[0];
	
	if (Math.abs(marginLeft-100) >= width) {
		right.addClassName('disabled');
		rightImg.src = rightImg.src.replace('right.png', 'right-disabled.png');
	} else {
		right.removeClassName('disabled');
		rightImg.src = rightImg.src.replace('-disabled', '');
	}
	if (marginLeft >= 0) {
		left.addClassName('disabled');
		leftImg.src = leftImg.src.replace('left.png', 'left-disabled.png');
	} else {
		left.removeClassName('disabled');
		leftImg.src = leftImg.src.replace('-disabled', '');
	}
};

var frontpageCarouselTimer;
var frontpageCarousel = function(ie) {
	var enable = !isMobile();
	if (!enable) {
		return;
	}
	var container = $('product-carousel-container');
	if (!container && !ie) {
		setTimeout(function(){
			frontpageCarousel(1);
		},200);
		return;
	}
	if (container.select('.post').size() > 1) {
		frontpageCarouselTimer = setInterval(moveSlides, 6000, 1);
	}
	//container.select('.post').each(function(el){
	//	el.fullText = el.select('p').reverse().first().innerHTML;
	//});
	
	//var alignRecipes = function() {
	//};
	Event.observe(document.onresize ? document : window, "resize", function(e){
		truncateSliderContent();
	});
	if (Prototype.Browser.IE) {
		return setTimeout(truncateSliderContent, 500);
	}
	truncateSliderContent();
};

var truncateSliderContent = function(init) {
	var container = $('product-carousel-container');
	var image = container.select('.image')[0];
	if (!init) {
		var firstSlideImg = image.select('.slides > .figure img')[0];
		Event.observe(firstSlideImg, 'load', function(e){
			truncateSliderContent(true);
		});
	}
	var imgHeight = image.getHeight();
	var setHeight = Math.floor( imgHeight-(imgHeight*0.12) );
	container.select('.post').each(function(el){
		el.setStyle({height:  setHeight + 'px'});
	});
};

var currentSlide = 0;

var moveSlides = function(n) {
	if (!n) {
		n = 1;
	}
	//console.log("moveslides");
	var container = $('product-carousel-container');
	var items = container.select('.post');
	var bullets = container.select('.bullets img');
	var slides = container.select('.slides').first();
	var totalitems = items.size();
	
	var marginLeft = parseInt(slides.getStyle('marginLeft').match(/-?(\d+)/ig)[0]);
	
	var nextitem = currentSlide + n;
	if (nextitem>=totalitems || nextitem < 0)
		nextitem = 0;
	
	var newMargin = -(100*nextitem);
	new Effect.Tween(null, marginLeft, newMargin,{duration:0.4}, function(m){
		slides.setStyle({marginLeft: m + '%'});
	});
	
	bullets.each(function(img){
		img.src = img.src.replace('-active','-inactive');
		if (img.hasClassName('post-'+nextitem+'-dot')) {
			img.src = img.src.replace('-inactive','-active');
		}
	});
	$$('.post-'+(currentSlide)+'-content')[0].fade({duration:0.2}).removeClassName('active');
	$$('.post-'+(currentSlide)+'-bottom')[0].fade({duration:0.2});
	setTimeout(function(){
		$$('.post-'+(nextitem)+'-content')[0].appear().addClassName('active');
		$$('.post-'+(nextitem)+'-bottom')[0].appear();
		setTimeout(function(){
			truncateSliderContent();
		},220);
		
	},200);
	currentSlide = nextitem;
};



var generateNav = function(container, ul, tag) {
	var count = 0;
	if (!container)
		return;
	container.select(tag).each(function(el,x){
		if (!el.hasClassName('nonav')) {
		el.identify();
		var li = new Element('li');
		var a = new Element('a',{href: 'javascript:;', onClick: "Effect.ScrollTo('" + el.id + "', {duration: 0.5, offset: -20})"}).update(el.innerHTML);
		li.insert(a);
		ul.insert(li);
		count++;
		}
	});
	if (count>0) {
		container.select('nav').invoke('show');
	}
};


var openItems = [];

var dropdowns = function(hi_i_am_a_retard_who_doesnt_respect_onload) {
	if (Prototype.Browser.IE && !hi_i_am_a_retard_who_doesnt_respect_onload) {
		return setTimeout(function(){ dropdowns(1); },500);
	}
	var temp = [];
	var mobile = isMobile();
	
	$$('.dropdown').each(function(div){
		var opener = div.select('a.opener')[0];
		if (!mobile) {
			opener.observe('mouseover', function(e){
				closeDropdowns();
				var cont = this.up(0);
				var menu = this.siblings('.menu')[0];
				cont.addClassName('active');
				menu.show();
				openItems.push(cont);
				dropdownWithFocus = cont;
			});
		}
		opener.observe('click', function(e){
			closeDropdowns();
			var cont = this.up(0);
			var menu = this.siblings('.menu')[0];
			cont.addClassName('active');
			menu.show();
			openItems.push(cont);
			dropdownWithFocus = cont;
		});
		
		
		div.close = function(event) {
			this.removeClassName('active');
			this.select('.menu')[0].hide();
		};
		
	});
};

var closeDropdowns = function() {
	openItems.each(function(open, x){
		open.close();
	});
};

document.observe('click',function(event){
	var clicked = event.element();
	//console.log(clicked.up('.opener'));
	var opener = clicked.up('.opener');
	openItems.each(function(open, x){
		//console.log(opener);
		if (!clicked.descendantOf(open) || clicked.hasClassName('hideonclick')) {
			open.close(event);
			delete openItems[x];
		}
	});
});
var dropdownWithFocus = null;
document.observe('mousemove', function(event){
	var el = event.element();
	var dropdown = el.up('.dropdown');
	if (dropdown == undefined && el.hasClassName('dropdown')) {
		dropdown = el;
	}
	if (dropdown) {
		
	} else if (dropdownWithFocus) {
		dropdownWithFocus.close(event);
		dropdownWithFocus = null;
	}
});


var recipeRecalc = function(val) {
	var quantity = $('recipe_quantity').getValue();
	
	switch(val) {
	case '+1':
		quantity++;
		break;
	case '-1':
		quantity--;
		break;
	default:
		quantity = val ? parseInt(val) : quantity;
		break;
	}
	quantity = (quantity>100 ? 100 : quantity);
	quantity = (quantity<=0  ? 1 : quantity);
	$('recipe_quantity').setValue(quantity);
	recipeIngredients.each(function(item){
		var newamount = parseFloat(item.amount*quantity);
		newamount = ( (newamount/parseInt(newamount) === 1) ? newamount : newamount.toFixed(1).replace('.',','));
		if (item.li.select('.amount')[0].hasClassName('unit-descvague')) {
			newamount = '&nbsp;';
		}
		item.li.select('.amount')[0].update( newamount );
	});
	var link = $('recipe_print_link').href.split("&");
	$('recipe_print_link').href = link[0] + "&servings=" + quantity;
}

var recipeIngredients = [];

var recipeInit = function() {
	$$('#recipe_ingredients li').each(function(li){
		var amount = parseFloat(li.select('.amount')[0].innerHTML.replace(',','.')).toFixed(2);
		recipeIngredients.push({li: li, amount: amount});
	});
	

	recipeRecalc();
	/*
	$('recipe_quantity_label').observe('click', function(){
		
	});
	*/
}
var bloginfo = function(option) {
	switch(option) {
	case 'url':
		return wp_siteurl;
	}
}
var productFilter = {category: null, meta: null, text: null, page: 0};

var filterProductlist = function(filter, value) {
	var categorylabel = $$('.select-category .opener .label')[0];
	var metataglabel  = $$('.select-metatag .opener .label')[0];
	if (filter == 'category' || productFilter.category !== null) {
		if (filter == 'category') productFilter.category = value;
		productFilter.meta = null;
		if (productFilter.category == '' || productFilter.category == null) {
			categorylabel.update('Kategori').removeClassName('selected');
		} else {
			categorylabel.update(category_slugs.get(productFilter.category)).addClassName('selected');
		}
		metataglabel.update('Egenskaper').removeClassName('selected');
	}
	if (filter == 'meta') {
		productFilter.meta = value;
		metataglabel.update(meta_slugs.get(productFilter.meta)).addClassName('selected');
	}
	
	if (filter == 'text') {
		//productFilter.category = null;
		//productFilter.meta = null;
		//categorylabel.update('Kategori').removeClassName('selected');
		//metataglabel.update('Egenskaper').removeClassName('selected');
		productFilter.text = value;
	}
	
	if (!wp_is_front_page) {
		document.location = wp_siteurl + '#!/productlist:' + productFilter.category + ';' + productFilter.meta + ';' + productFilter.text + ';' + productFilter.page;
	} else {
		$('filterproducts_text').setValue(value);
	}
	
	var container = $$('.products')[0];
	if (typeof(container) === undefined) {
		//document.location.hash = '#!/productlist:' + productFilter.category + ';' + productFilter.meta + ';' + productFilter.text + ';' + productFilter.page;
	}
	
	Effect.ScrollTo(container, {offset:-70});
	new Ajax.Request(bloginfo('url')+'/',{
		parameters: {action: 'getproducts', category:productFilter.category, meta: productFilter.meta, text: productFilter.text},
		onSuccess: function(transport) {
			container.update(transport.responseText);
			
			productSlideBtns($('productgrid'));
			
			document.location.hash = '#!/productlist:' + productFilter.category + ';' + productFilter.meta + ';' + productFilter.text + ';' + productFilter.page;
			swipe(null,$('productgrid'), productFilter.page);
		}
	});
}

var initProductlist = function() {
	var filter = document.location.hash.replace(/#!\//, "").split('productlist:');
	if (filter[1]) {
		filter = filter[1].split(';');
		productFilter.category = (filter[0]==''||filter[0]=='null' ? null : filter[0]);
		productFilter.meta = (filter[1]=='null' ? null : filter[1]);
		productFilter.text = (filter[2]=='null' ? null : filter[2]);
		productFilter.page = filter[3];
		var search,value;
		if (productFilter.category !== null) {
			search = 'category'; value = productFilter.category; 
		}
		if (productFilter.meta !== null) {
			search = 'meta'; value = productFilter.meta;
		}
		if (productFilter.text !== null) {
			search = 'text'; value = productFilter.text;
		}
		filterProductlist(search, value);
	}
	
}


var btnstates = function() {
	var preload = new Array();
	
	$$('.btnstates').each(function(img){
		var url = img.src.substring(0,img.src.length-4);
		
		['hover','click'].each(function(s){
			var src = url + '-' + s + '.png';
			preload.push(src);
		});
		
		/* Events */
		img.up(0).observe('mouseover',function(el){
			img.src = url + '-hover.png';
		});
		img.up(0).observe('mouseout',function(el){
			img.src = url + '.png';
		});
		img.up(0).observe('mousedown',function(el){
			img.src = url + '-click.png';
		});
		img.up(0).observe('mouseup',function(el){
			img.src = url + '-hover.png';
		});
	});
	
	/* Preloading */
	preload.uniq().each(function(url){
		var img = new Image();
		img.src = url;
		img.onload = function() {
		};
	});
	
	$$('.slides').each(function(s){
		
		s.touch = false;
		s.startPos = 100;
		
		s.observe('touchstart',function(e){
			s.touch = true;
			var touchstart = (touch.clientX/viewport.width)*(100);
			var marginLeft = s.getStyle('marginLeft').match(/-?(\d+)/ig);
			s.startPos = Math.abs(parseInt(marginLeft[0]));
			
			return;
		});
		s.observe('touchmove', function(e){
			if (!s.touch) return;
			var touch = e.touches[0];
			var offset = (touch.clientX/viewport.width)*(100);
			offset = offset-s.startPos;
			s.setStyle({marginLeft: offset + '%'});
			
			return;
		});
		s.observe('touchend', function(e){
			var marginLeft = s.getStyle('marginLeft').match(/-?(\d+)/ig);
			offset = parseInt(marginLeft[0]); 
			var rounded = Math.round(offset/100)*100;
			s.setStyle({marginLeft: '' + rounded + '%'});
			s.startPos = rounded;
			s.touch = false;
		});
		
		
	});
};

var peoplelists = function() {

	var mobile = isMobile();
	$$('.vcard').each(function(vcard){
		mobile ? null : vcard.select('.btn-phone')[0].up('li').remove();
	});
};

var isMobile = function() {
	var agent = navigator.userAgent.toLowerCase();
	return !!(agent.match(/(iPhone|iPod|blackberry|android 0.5|htc|lg|midp|mmp|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i));
}

var viewport;

var debug = function() {
	var body = $$('body')[0];
	var debug = new Element('div',{id: 'debug', style: 'position: fixed;top:0;left:0;width:50%;height:auto;color:#000;background-color:#fff;opacity:0.8'});
	body.insert(debug);
	
	debug.update("hei");
	/*
	var onresize = function() {
		viewport = document.viewport.getAltDimensions();
		$('debug').update('width: ' + viewport.width + "<br/>\n" + 'height: ' + viewport.height);
	};
	
	Event.observe(document.onresize ? document : window, "resize", function(e){
		onresize();
	});
	onresize();
	*/
};

FastInit.addOnLoad(btnstates, frontpageCarousel, initProductlist, peoplelists, dropdowns);












function substr (str, start, len) {
    // Returns part of a string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/substr
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // +      revised by: Theriault
    // +      improved by: Brett Zamir (http://brett-zamir.me)
    // %    note 1: Handles rare Unicode characters if 'unicode.semantics' ini (PHP6) is set to 'on'
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: false
    // *       example 3: ini_set('unicode.semantics',  'on');
    // *       example 3: substr('a\uD801\uDC00', 0, -1);
    // *       returns 3: 'a'
    // *       example 4: ini_set('unicode.semantics',  'on');
    // *       example 4: substr('a\uD801\uDC00', 0, 2);
    // *       returns 4: 'a\uD801\uDC00'
    // *       example 5: ini_set('unicode.semantics',  'on');
    // *       example 5: substr('a\uD801\uDC00', -1, 1);
    // *       returns 5: '\uD801\uDC00'
    // *       example 6: ini_set('unicode.semantics',  'on');
    // *       example 6: substr('a\uD801\uDC00z\uD801\uDC00', -3, 2);
    // *       returns 6: '\uD801\uDC00z'
    // *       example 7: ini_set('unicode.semantics',  'on');
    // *       example 7: substr('a\uD801\uDC00z\uD801\uDC00', -3, -1)
    // *       returns 7: '\uD801\uDC00z'
    // Add: (?) Use unicode.runtime_encoding (e.g., with string wrapped in "binary" or "Binary" class) to
    // allow access of binary (see file_get_contents()) by: charCodeAt(x) & 0xFF (see https://developer.mozilla.org/En/Using_XMLHttpRequest ) or require conversion first?
    var i = 0,
        allBMP = true,
        es = 0,
        el = 0,
        se = 0,
        ret = '';
    str += '';
    var end = str.length;

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT
    switch ((this.php_js.ini['unicode.semantics'] && this.php_js.ini['unicode.semantics'].local_value.toLowerCase())) {
    case 'on':
        // Full-blown Unicode including non-Basic-Multilingual-Plane characters
        // strlen()
        for (i = 0; i < str.length; i++) {
            if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
                allBMP = false;
                break;
            }
        }

        if (!allBMP) {
            if (start < 0) {
                for (i = end - 1, es = (start += end); i >= es; i--) {
                    if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
                        start--;
                        es--;
                    }
                }
            } else {
                var surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
                while ((surrogatePairs.exec(str)) != null) {
                    var li = surrogatePairs.lastIndex;
                    if (li - 2 < start) {
                        start++;
                    } else {
                        break;
                    }
                }
            }

            if (start >= end || start < 0) {
                return false;
            }
            if (len < 0) {
                for (i = end - 1, el = (end += len); i >= el; i--) {
                    if (/[\uDC00-\uDFFF]/.test(str.charAt(i)) && /[\uD800-\uDBFF]/.test(str.charAt(i - 1))) {
                        end--;
                        el--;
                    }
                }
                if (start > end) {
                    return false;
                }
                return str.slice(start, end);
            } else {
                se = start + len;
                for (i = start; i < se; i++) {
                    ret += str.charAt(i);
                    if (/[\uD800-\uDBFF]/.test(str.charAt(i)) && /[\uDC00-\uDFFF]/.test(str.charAt(i + 1))) {
                        se++; // Go one further, since one of the "characters" is part of a surrogate pair
                    }
                }
                return ret;
            }
            break;
        }
        // Fall-through
    case 'off':
        // assumes there are no non-BMP characters;
        //    if there may be such characters, then it is best to turn it on (critical in true XHTML/XML)
    default:
        if (start < 0) {
            start += end;
        }
        end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
        // PHP returns false if start does not fall within the string.
        // PHP returns false if the calculated end comes before the calculated start.
        // PHP returns an empty string if start and end are the same.
        // Otherwise, PHP returns the portion of the string from start to end.
        return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
    }
    return undefined; // Please Netbeans
}

