// remap jQuery to $
//doTimeout function
(function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var f=d.call(arguments),e=b.apply(this,[c+f[0]].concat(f));return typeof f[0]==="number"||typeof f[1]==="number"?this:e};function b(l){var m=this,h,k={},g=l?$.fn:$,n=arguments,i=4,f=n[1],j=n[2],p=n[3];if(typeof f!=="string"){i--;f=l=0;j=n[1];p=n[2]}if(l){h=m.eq(0);h.data(l,k=h.data(l)||{})}else{if(f){k=a[f]||(a[f]={})}}k.id&&clearTimeout(k.id);delete k.id;function e(){if(l){h.removeData(l)}else{if(f){delete a[f]}}}function o(){k.id=setTimeout(function(){k.fn()},j)}if(p){k.fn=function(q){if(typeof p==="string"){p=g[p]}p.apply(m,d.call(n,i))===true&&!q?o():e()};o()}else{if(k.fn){j===undefined?e():k.fn(j===false);return true}else{e()}}}})(jQuery);

var pathvar = "";
if(window.location.host == 'localhost'){
	pathvar = "/joost";
};
function make_postcode($){
	if($('#same-shipping').is(':checked')){
		city = $("#billing-city").val();
		postcode = $("#billing-postcode").val();
	}else{
		city = $("#shipping-city").val();
		postcode = $("#shipping-postcode").val();
	}
	data = 	{'cart':'true','update':'Update Subtotal','shipping':{'postcode': postcode , 'city': city, 'country':'AU'}};
	$.post("//"+location.hostname+pathvar+"/store/cart/", data, function(data){
		price = $(data).find("#checkoutdata").text();
		data = eval(price);
		var price;
		$.each(data, function(index, val){
			if(val.ship){
				price = val;
			}
		})
		$(".shopp_cart_subtotal").html(price.sub); 
		if (price.ship != "Enter Postal Code"){
			$(".shopp_cart_shipping").html(price.ship)
		}else{
			alert("error calculating shipping \n please check destination town and postcode are valid");
		}; 
		$(".shopp_cart_tax").html(price.tax); 
		$(".shopp_cart_total").html(price.tot); 
	})
};

(function($){
	$("#update_p_c").click(function(e){
		e.preventDefault();
		make_postcode($)
	});
	//logic for shipping calculator
  	$( "#billing-postcode, #billing-city" ).autocomplete({
			source: function( request, response ) {
				$.ajax({
						url: "http://api.fastway.org/latest/psc/listdeliverysuburbs/MEL/"+request.term+".jsonp?api_key=ef5b98b2b80e01183e73eac7a3b4b3b8&callback=?", 
						dataType: 'jsonp',
						success: function(data){
									if (data.result.length == 0){
										response([{label:"No Results Found",value:""}]);
									} else {
										response( $.map( data.result, function( item, index ) {
												if(index <= 25){
													return {
														label: item.label,
														value: { pcode : item.Postcode, town : item.Town, state: item.State}
													}
												}else{
													return false;
												}
											}
									))};
									$('input').removeClass('ui-autocomplete-loading');
									},
						error: function(){}
						})
			},
			minLength: 1,
			select: function( e, ui ) {
				e.preventDefault();
				if(ui.item.value != ''){
					$("#billing-postcode").val(ui.item.value.pcode);
					$("#billing-city").val(ui.item.value.town);
					$("#billing-state-menu").val(ui.item.value.state);
					make_postcode($)
				}else{
					$("#billing-postcode").val('');
					$("#billing-city").val('');
				}
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			},
			focus: function(e, ui){
				e.preventDefault();
				if(ui.item.value != ''){
					$("#billing-postcode").val(ui.item.value.pcode);
					$("#billing-city").val(ui.item.value.town);
					$("#billing-state-menu").val(ui.item.value.state);
				}else{
					$("#billing-postcode").val('');
					$("#billing-city").val('');
				}
							
			}
		});
	// cart page and shipping
	$( "#cart #shipping-postcode, #cart #shipping-city" ).focus(function(e){e.preventDefault();$(this).val("")})
  	$( "#shipping-postcode, #shipping-city" ).autocomplete({
			source: function( request, response ) {
				$.ajax({
						url: "http://api.fastway.org/latest/psc/listdeliverysuburbs/MEL/"+request.term+".jsonp?api_key=ef5b98b2b80e01183e73eac7a3b4b3b8&callback=?", 
						dataType: 'jsonp',
						success: function(data){
									if (data.result.length == 0){
										response([{label:"No Results Found",value:""}]);
									} else {
									response( $.map( data.result, function( item, index ) {
											if(index <= 25){
												return {
													label: item.label,
													value: {  pcode : item.Postcode, town : item.Town, state: item.State}
												}
											}else{
												return false;
											}
										}
									))};
									$('input').removeClass('ui-autocomplete-loading');
									},
						error: function(){}
						})
			},
			minLength: 1,
			select: function( e, ui ) {
				e.preventDefault();
				if(ui.item.value != ''){
					$("#shipping-postcode").val(ui.item.value.pcode);
					$("#shipping-city").val(ui.item.value.town);
					$("#shipping-state-menu").val(ui.item.value.state);

					if($("form#cart").length >= 1){
						//$("form#cart").submit();
						make_postcode($)
					}else{
						make_postcode($)
					}
				}else{
					$("#shipping-postcode").val('');
					$("#shipping-city").val('');
				}
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			},
			focus: function(e, ui){
				e.preventDefault();
				if(ui.item.value != ''){
					$("#shipping-postcode").val(ui.item.value.pcode);
					$("#shipping-city").val(ui.item.value.town);
					$("#shipping-state-menu").val(ui.item.value.state);
				}else{
					$("#shipping-postcode").val('');
					$("#shipping-city").val('');
				}
							
			}
		});
	$( "#carttown" ).css({'width':'280','display':'block'}).focus(function(e){e.preventDefault();$(this).val("")});
	$("#postcode-input").css({'display':'none'});
  	$( "#carttown" ).autocomplete({
			source: function( request, response ) {
				$.ajax({
						url: "http://api.fastway.org/latest/psc/listdeliverysuburbs/MEL/"+request.term+".jsonp?api_key=ef5b98b2b80e01183e73eac7a3b4b3b8&callback=?", 
						dataType: 'jsonp',
						success: function(data){
									if (data.result.length == 0){
										response([{label:"No Results Found",value:""}]);
									} else {
									response( $.map( data.result, function( item, index ) {
											if(index <= 25){
												return {
													label: item.label,
													value: {  pcode : item.Postcode, town : item.Town, state: item.State}
												}
											}else{
												return false;
											}
										}
									))};
									$('input').removeClass('ui-autocomplete-loading');
									},
						error: function(){}
						})
			},
			minLength: 1,
			select: function( e, ui ) {
				e.preventDefault();
				if(ui.item.value != ''){
					if($('#same-shipping').is(':checked')){
						$("#billing-postcode, #shipping-postcode").val(ui.item.value.pcode);
						$("#billing-city, #shipping-city").val(ui.item.value.town);
						$("#billing-state-menu, #shipping-state-menu").val(ui.item.value.state);
					}else{
						$("#shipping-postcode").val(ui.item.value.pcode);
						$("#shipping-city").val(ui.item.value.town);
						$("#shipping-state-menu").val(ui.item.value.state);
					}
					$(this).val(ui.item.value.town+", "+ui.item.value.pcode+", "+ui.item.value.state);
					make_postcode($);
				}else{
					$("#shipping-postcode").val('');
					$("#shipping-city").val('');
				}
			},
			open: function() {
				$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
			},
			close: function() {
				$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
			},
			focus: function(e, ui){
				e.preventDefault();
				if(ui.item.value != ''){
					$("#shipping-postcode").val(ui.item.value.pcode);
					$("#shipping-city").val(ui.item.value.town);
					$("#shipping-state-menu").val(ui.item.value.state);
					$(this).val(ui.item.value.town+", "+ui.item.value.pcode+", "+ui.item.value.state);
				}else{
					$("#shipping-postcode").val('');
					$("#shipping-city").val('');
				}
							
			}
		});
		// end shipping

var x = '';
var processor = {
  timerCallback: function() {
  	console.log('timer call');
    $.doTimeout(15000, function() {
    	//console.log('doTimeout started');
    	$('#gridoverlay').clearQueue();
    	processor.computeFrame();
    });
  },
  onLoad: function(){
  	console.log('k');
  	processor.count = 1;
  	processor.imagearray = new Array();
  	//x = this;
  	$('li img.headerimg').each(function(){
  		processor.imagearray.push($(this).attr('src'));
  	});
  	processor.timerCallback();
  },
  computeFrame: function(){
  	// $('#gridoverlay div').css({
  	// 	display:'none'
  	// });

  	$('#gridoverlay').fadeIn('slow', function(){
  		var blocks = [];
		$('#gridoverlay div').each(function(){
			//console.log($(this).css('background-position'));
			var $newobj = $('<div class="removeable" style="background-image:url('+processor.imagearray[processor.count]+'); background-position:'+$(this).css('background-position')+'; display:none "></div>');
			$(this).append($newobj);
			
			//'background-image':'url('+x.imagearray[x.count]+') !important'
		});
		blocks = $('.removeable');
		
		//blocks = blocks.slice(0,11);
		//console.log(blocks);
		//for(var i=0; i<blocks.length;i++){
			
			//console.log(blocks[i]);
		//}
		var randomarr = new Array(0,1,2,3,4,5,6,7,8,9,10,11);
		function randOrd(){
			return(Math.round(Math.random())-0.5);
		}
		randomarr.sort(randOrd);
		var i = 0;
		$('#currentview').css({'background-image':'url('+processor.imagearray[processor.count]+')'});
		$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
			$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
				$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
					$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
						$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
							$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
								$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
									$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
										$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
											$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
												$(blocks[randomarr[i++]]).fadeIn('slow').doTimeout(100, function(){
													$(blocks[randomarr[i++]]).fadeIn('slow').queue(function(){
														$('#gridoverlay').fadeOut('slow').queue(function(){
																$('#gridoverlay div').css({'background-image':$('.removeable').css('background-image')});
																$('.removeable').remove();
																processor.count++;
																if(processor.count == processor.imagearray.length){
																	processor.count = 0;
																}
																console.log('completed');
																processor.timerCallback();
		});
			
		});
		});
		});
		});
		});
		});
		});
		});
		});		
		});
		});
		});
		
		
		
	});
  }



}
// init vars


// ajax shopp handler

/*
var ShoppCartAjaxHandler = function (cart) {
	console.log('click')
	var display = $('#shopp-cart-ajax');
	display.empty().hide(); // clear any previous additions
	var item = $('<ul></ul>').appendTo(display);
	if (cart.Item.thumbnail)
		$('<li><img src="'+cart.Item.thumbnail.uri+'" alt="" width="'+cart.Item.thumbnail.width+'"  height="'+cart.Item.thumbnail.height+'" /></li>').appendTo(item);
	$('<li></li>').html('<strong>'+cart.Item.name+'</strong>').appendTo(item);
	if (cart.Item.optionlabel.length > 0)
		$('<li></li>').html(cart.Item.optionlabel).appendTo(item);
	$('<li></li>').html(asMoney(cart.Item.unitprice)).appendTo(item);

	if ($('#shopp-cart-items').length > 0) {
		$('#shopp-cart-items').html(cart.Totals.quantity);
		$('#shopp-cart-total').html(asMoney(cart.Totals.total));			
	} else {
		$('.widget_shoppcartwidget p.status').html('<a href="'+cart.url+'"><span id="shopp-cart-items">'+cart.Totals.quantity+'</span> <strong>Items</strong> &mdash; <strong>Total</strong> <span id="shopp-cart-total">'+asMoney(cart.Totals.total)+'</span></a>');
	}
	display.slideDown();
}
*/
// ajax loader for single shop
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};



var inith = 435;
var initp = 40;

function productInit(e){
	//alert('test')
	//console.log(e);
	$("#shopp #ajax_product #product-title .right").click('click', function(){
		$("#shopp #ajax_product #product-title").css('display','none');
		$("#shopp #ajax_product #product-overlay").css('display', 'block')
	})
	$("#shopp #ajax_product #product-overlay .right").click('click', function(){
		$("#shopp #ajax_product #product-overlay").css('display','none');
		$("#shopp #ajax_product #product-title").css('display', 'block')
	})

	$("#shopp #ajax_product div.text.full").css('display','none');
	$("#shopp #ajax_product div.text.summary").css('display','block');
	var fh = $('#product-overlay form').height();
	//console.log(fh);
	var height = $("#product-overlay").height();
	fh = (Math.ceil(fh/10)+1)*10;
	$("#product-overlay").css({'padding-bottom': fh+'px'});
	//inith = inith - (fh - initp) - 15;
	$("#shopp #ajax_product #product-overlay").css('display','none');
	$("#shopp #ajax_product #product-title").css('display', 'block')

	$("a#show_fulltext").click(function(e){
		$("#product-overlay").animate({'height':inith-fh+40+'px'},"fast")
		$("#shopp #ajax_product div.text.summary").fadeOut('fast',function(){
			$("#shopp #ajax_product div.text.full").fadeIn('fast');
		});
		e.preventDefault()
	})
	$("a#show_lesstext").click(function(e){
		$("#product-overlay").animate({'height':height},"fast")
		$("#shopp #ajax_product div.text.full").fadeOut('fast',function(){
			$("#shopp #ajax_product div.text.summary").fadeIn('fast');
		});
		e.preventDefault()
	})
	$('#shopp-single input.addtocart.ajax').click(function(e){
		var button = $(this);
		button.attr('value', "Adding...");
		$.post("//"+location.hostname+pathvar+"/store/cart/", $("form.shopp.product.single").serialize(), function(data) {
	   		//console.log(data);
	   		//data.prototype.toJSON;
	   		//console.log($("form.shopp.product.single").serialize());

	   		data = JSON.parse(data);
	   		console.log(data);
	   		
	   		var ajaxresponse = '{'; 
ajaxresponse+=	'"Item": {';
ajaxresponse+=		'"category": 1,';
ajaxresponse+=		'"data": [],';
ajaxresponse+=		'"description": "",';
ajaxresponse+=		'"donation": {},';
ajaxresponse+=		'"download": 1, '	;
ajaxresponse+=		'"freeshipping": "",';
ajaxresponse+=		'"inventory": false,';
ajaxresponse+=		'"menus": {},	'	;
ajaxresponse+=		'"name": "'+data.Item.name+'",';
ajaxresponse+=		'"option": {},';
ajaxresponse+=		'"optionlabel":"",';
ajaxresponse+=		'"price": '+data.Item.priced+',	';	
ajaxresponse+=		'"product": 1,';		
ajaxresponse+=		'"quantity": 1,';	
ajaxresponse+=		'"sale": false,';	
ajaxresponse+=		'"saved": 0,';		
ajaxresponse+=		'"savings": 0,';			
ajaxresponse+=		'"shipfee": 0,';			
ajaxresponse+=		'"shipping": false,';	
ajaxresponse+=		'"sku": "",'	;		
ajaxresponse+=		'"slug": "product",';	
ajaxresponse+=		'"tax": '+data.Item.pricedtax+',	';			
ajaxresponse+=		'"taxable": true,';		
ajaxresponse+=		'"thumbnail": {';
ajaxresponse+=			'"uri":"'+data.imguri+data.Item.image.id+'?145,145,2,478942387",';//+'/'+data.Item.image.filename+'?145,145,1,3851978124
ajaxresponse+=			'"width":145,';//'+data.Item.image.width+'
ajaxresponse+=			'"height":145';//'+data.Item.image.height
ajaxresponse+=		'},'	;
ajaxresponse+=		'"total": 1.00000000,';	
ajaxresponse+=		'"type": "Download",'	;
ajaxresponse+=		'"unitprice": 1.0000,';	
ajaxresponse+=		'"weight": 0'	;		
ajaxresponse+=	'},';
ajaxresponse+=	'"Totals": {';
ajaxresponse+=		'"discount": 0,';		
ajaxresponse+=		'"quantity": '+data.Totals.quantity+',';		
ajaxresponse+=		'"shipping": 1.00000,';	
ajaxresponse+=		'"subtotal": 1.00000,';	
ajaxresponse+=		'"tax": 0,';				
ajaxresponse+=		'"taxed": 0,';			
ajaxresponse+=		'"taxrate": 0.15,';		
ajaxresponse+=		'"total": '+data.Totals.total+'';		
ajaxresponse+=	'},';
ajaxresponse+=	'"url": "'+data.url+'"	';
ajaxresponse+=	'}';	
			//console.log(ajaxresponse);
		   	//ajaxresponse = JSON.parse(ajaxresponse);
		   	//console.log(ajaxresponse);
	   		ShoppCartAjaxHandler(data);
			button.attr('value',"Add to Cart");

	 	});			
	 e.preventDefault();
	})
	if($("#slideshow .items").length >= 2){
		$("#slideshow").hover(
			function(){
				$(this).prepend('<h2 id="rofb" >click for next image</h2>');
			},
			function(){
				$("#rofb").remove()
			}
		);
	}
/*
	$("#slideshow .items").cycle({
		speed:  300,
		timeout: 0,
		sync: 1,
		pager: "#thumbs",
		next:   '#slideshow .items',
		fx: 'scrollDown' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
	})
*/
	$("#slideshow").scrollable({ vertical: true, mousewheel: false }).navigator({
		navi: "#thumbs",
		naviItem: 'a'
	});
	$("#ajax_product select").not('.addtocart select').styledSelect();

}
/* trigger when page is ready */

	$("#featurewrap").cycle({
		speed:  500,
		timeout: 8000,
		sync: 1,
		fx: 'scrollDown' // choose your transition type, ex: fade, scrollUp, shuffle, etc...
	})

var div_code = '<div class="pic"></div>';

var slide_height = 0;
var imgref = '';

function load_img(href, pointer){
		//console.log(pointer.find('div.pic').hasClass('pic'));
		
		if (slide_height == 0){pointer.find('div.pic').animate({height:'145px'},'fast',function(){
			pointer.prepend("<div style='display:block' id='load'><h3 class='remove'>Loading...</h3></div>");
		})}else{
			pointer.prepend("<div style='display:block' id='load'><h3 class='remove'>Loading...</h3></div>");
		}
		pointer.find('div.pic').load(href+" #attachID",function(e){
			
			console.log(slide_height);
			//console.log(pointer.find('div.pic').html());//.find('.attachment-4w-article-img').attr('class')
			slide_height = $(this).find('#attachID').height()+20;
			$(this).prepend('<div class="hoverstate" style="margin-left:'+($(this).find('img').width()-70)+'px">close X</div>');
			$(this).animate({
					height	:	slide_height,
					opacity :   1
			},'500',function(){$("#load").remove()});
		})
}



	// Binds
	$('.article_gallery a').click(function(e){
		var thisbox = $(this).parent();
		thisbox.find('.active').each(function(){
			$(this).removeClass('active');
		})
		$(this).addClass('active');
		if(thisbox.find('div.pic').length == 0){
			$(div_code).prependTo(thisbox);
		}
		// $('.article_gallery a').not($(this)).animate({
		// 			opacity :   .5
		// 	},'500');
		imgref = this;
		// $(this).animate({
		// 	opacity : 1
		// },'500');
		//console.log(thisbox.find('div.pic').hasClass('pic'));
		thisbox.find('div.pic').animate({
				height: slide_height,
				opacity: 0
		},{
				duration:  '500',
				complete: function(e){ load_img($(imgref).attr('href'), thisbox)}
		})
		e.preventDefault();
	});

	$('div.pic').live('click', function(e){
		if(e.target.className=='hoverstate'){
			return false;
		}
		var flag = 0;
		var imagearr = [];
		$(this).parent().find('a').each(function(){
			imagearr.push(this);
		});
		for(var i=0;i<imagearr.length;i++){
			if($(imagearr[0]).hasClass('active')){
				break;
			}
			else{
				var tmp = imagearr.shift();
				imagearr.push(tmp);
			}
		}
		$(imagearr).each(function(){
			if(flag == 1){
				var thisbox = $(this).parent();
				thisbox.find('.active').each(function(){
					$(this).removeClass('active');
				})
				$(this).addClass('active');
				if(thisbox.find('div.pic').length == 0){
					$(div_code).prependTo(thisbox);
				}
				// $('.article_gallery a').not($(this)).animate({
				// 			opacity :   .5
				// 	},'500');
				imgref = this;
				// $(this).animate({
				// 	opacity : 1
				// },'500');
				thisbox.find('div.pic').animate({
						height: slide_height,
						opacity: 0
				},{
						duration:  '500',
						complete: function(e){load_img($(imgref).attr('href'), thisbox)}
				})
				flag = 2;
			}
			if($(this).hasClass('active') && flag != 2){
				flag = 1;
			}
		});
	})

	$('div.pic .hoverstate').live('click', function(e){
		$(this).parent().animate({
			height: 0,
			opacity: 0
		});
		// $('.article_gallery a').animate({
		// 	opacity: 1
		// });
		slide_height = 0;
	});
	// bind to single click in shopp

	//handle redirects from product pages.
	var hashtag = window.location.hash;
	//console.log(window.location.protocol + "//" + window.location.host+window.location.pathname+hashtag);
	if(hashtag.length >= 1){
		hashtag = hashtag.replace('#','');
	 	$("#shopp-single").load(window.location.protocol + "//" + window.location.host+window.location.pathname+hashtag+" #ajax_product", function(e){
	 		
	 		productInit(e)
	 	});	
	}
	
	
	$("#shopp .product .name a, #shopp .product .frame a:not(.enquirelink)").live('click', function(e){
		//ajax-hidden-loader
		$('#shopp-single .item img').attr('src',window.location.protocol + "//" + window.location.host+'/wp-content/themes/Joost/images/load-black.gif');
		$('#shopp-single .item img').attr('width','auto');
		$('#shopp-single .item img').attr('height', 'auto');
		$('html, body').animate({scrollTop: $('.category').offset().top-20}, 200);
		$.get($(this).attr('href'), function(data){
			//console.log(data);
			//console.log(data.substring(data.indexOf('<div id="ajax_product">'),data.indexOf('</div><div id="shopp-cart-ajax"')));
			// $('#ajax-hidden-loader').html(data);
			var insertion = data.substring(data.indexOf('<div id="ajax_product">'),data.indexOf('<div id="shopp-cart-ajax"'));
			//insertion = insertion.substring(0,insertion.lastIndexOf('</div>'));
			 $('#shopp-single').html(insertion);
			// $('#ajax-hidden-loader').empty();
			productInit();
			
			
		})
		// $("#shopp-single").load($(this).attr('href')+" #ajax_product", function(e){
		// 		//console.log(e);
		// 		productInit(e)
		// 	});	
		e.preventDefault()
	});

	$('#otherthings').click(function(e){
		button = $(this);
		button.text('Loading...');
		var od = $('#otherthings-ajax').attr('offset-data');
		od===undefined?od=$('.offset-data').attr('offset-data'):od;
		if(od!='none'){
			od+=18;
			//serializeObject
			var id_array = [];
			$('.ot-block').each(function(){
				id_array.push(parseInt($(this).attr('post-id')));	
			});
			var serialized = serialize(id_array);
			var data = {
				action: 'ajaxcall',
				offset: od,
				postidz: serialized
			};
			jQuery.post(pathvar+'/wp-admin/admin-ajax.php', data, function(response) {
				
				$('#otherthings-ajax').append(response)
				var offset = $('.offset-data').attr('offset-data');
				$('#otherthings-ajax').attr('offset-data',offset);
				$('.offset-data').remove();
				//console.log($('#otherthings-ajax'));
				//console.log(offset);
				button.text('show more');

			});
		}
		else{
			$(this).text('No more to show.');
		}
		e.preventDefault();
	});

	
	$('#recentposts.post').live('click', function(e){
		$('#recentposts.post').parent("h3").replaceWith("<h3 class='remove'>loading...</h3>")

		var od = parseInt($('#recent-offset').attr('offset'));
		ex_id = $('#recent-offset').attr('data-exclude');
		var data = {
			action: 'ajaxcall',
			recent: od,
			ex: ex_id
		};
		jQuery.post(pathvar+'/wp-admin/admin-ajax.php', data, function(response) {
			$('#recent-offset').remove();
			$('h3.remove').remove();
			$('#recent-ajax').html($('#recent-ajax').html()+response);
			console.log(data);
			console.log(response);
		})
		e.preventDefault();
	});
	$('#recentposts.cat').live('click', function(e){
		var cat = $('#recentposts.cat').attr('data-category');
		
		$('#recentposts.cat').parent("h3").replaceWith("<h3 class='remove'>loading...</h3>")

		var od = parseInt($('#recent-offset').attr('offset'));
		var data = {
			action: 'ajaxcall',
			recent: od,
			category: cat
		};
		jQuery.post(pathvar+'/wp-admin/admin-ajax.php', data, function(response) {
			$('#recent-offset').remove();
			$('h3.remove').remove();
			$('#recent-ajax').append(response);
		})
		e.preventDefault();
	})
/*
	$('#recentposts.cat').live('click', function(e){
		var thisbutton = this;
		var cat = $('#recentposts.cat').data('category');
		var od = parseInt($('#recent-offset').attr('offset'));
		//console.log(od);
		if(od!==NaN && $(this).text() != 'No more to show.'){
			//od+=18;
			//serializeObject
			
			var data = {
				action: 'ajaxcall',
				recent: od,
				category: cat
			};
			jQuery.post(pathvar+'/wp-admin/admin-ajax.php', data, function(response) {
				$('#recent-offset').remove();
				

				if(response == 'none' || response == false){
					$(thisbutton).text('No more to show.');
					
				}
				else{

					$('#recent-ajax').append(response);
				}
			});
		}
		else{
			$(this).text('No more to show.');
		}
		e.preventDefault();
	})
*/
	// bind remove link in ajax shopping cart
	$("#cartview .cartblock a.remove").live('click',function(e){
		var product = $(this).attr('data-prod');
		var quanrem = parseInt($('#items-'+product+'-quantity').attr('value'));
		var quancur = parseInt($('#items-'+product+'-quantity').parent().attr('data-quan'));
		$(this).replaceWith("<p class='remove'>Removing...</p>");
		e.preventDefault();
		href = $(this).attr('href');
		href = href.split("?");
		$.get(pathvar+"/store/cart/", href[1]+(quanrem-quancur), function(){
			ShoppCartAjaxHandler();
		})
	})

var sortajax = true;
$('a.rellink').live('click', function(e){
	e.preventDefault();
	if(sortajax == true){
		sortajax = false;
		$('#ajax-hidden-loader').load(e.target.href+ " .products", function(e){
			$(".products").replaceWith($('#ajax-hidden-loader').children());
			sortajax = true;
		})
	}
})


/* optional triggers

$(window).load(function() {
	
});

$(window).resize(function() {
	
});

*/
if($('#shopp-cart-ajax').length != 0){
	cartscroll();
}

})(window.jQuery);

function amazingheader(){
	processor.onLoad();
}



/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.3-pre
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener )
            for ( var i=types.length; i; )
                this.addEventListener( types[--i], handler, false );
        else
            this.onmousewheel = handler;
    },
    
    teardown: function() {
        if ( this.removeEventListener )
            for ( var i=types.length; i; )
                this.removeEventListener( types[--i], handler, false );
        else
            this.onmousewheel = null;
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});


function handler(event) {
    var args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true;
    
    event = $.event.fix(event || window.event);
    event.type = "mousewheel";
    
    if ( event.wheelDelta ) delta = event.wheelDelta/120;
    if ( event.detail     ) delta = -event.detail/3;
    
    // Add event and delta to the front of the arguments
    args.unshift(event, delta);

    return $.event.handle.apply(this, args);
}

})(jQuery);

function cartscroll(){
	(function($) {
	    //http://jsfiddle.net/smCkB/11
	    //Get our elements for faster access and set overlay width
	    $('#shopp-cart-ajax').slideDown();
	    var div = $('div.cartviewholder'),
	        ul = $('ul#cartview'),
	        ulWidth = ul.width();
	    ulPadding = 0;
	    var scrollWheelTotal = 0;

	    //Get menu width
	    var divWidth = div.width();

	    //Remove scrollbars     
	    div.css({
	        overflow: 'hidden'
	    });

	    //Find last image container
	    var lastLi = ul.find('li:last-child');

	    //When user move mouse over menu
	    div.mousemove(function(e) {

	        //As images are loaded ul width increases,
	        //so we recalculate it each time
	        var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;
	        var left = (e.pageX - div.offset().left) * (ulWidth - divWidth) / divWidth;

	        //$("#ulwidth").empty().append("ulWidth: " + ulWidth + " = lastLi[0].offsetLeft :" + lastLi[0].offsetLeft + " + lastLi.outerWidth(): " + lastLi.outerWidth() + " + ulPadding :" + ulPadding)
	        //$("#left").empty().append("left: " + left + "= (e.pageX :" + e.pageX + "- div.offset().left: " + div.offset().left + ") * (ulWidth :" + ulWidth + " - divWidth: " + divWidth + ") / divWidth: " + divWidth);

	        div.scrollLeft(left);
	    });
	    // $("a").hover(function() {
	    //     $(this).append("<img class='delete' src='http://dummyimage.com/20x20/FF0000/fff&text=X'/>");

	    //     $(".delete").click(function() {
	    //         $(this).closest("li").remove();
	    //     });
	    // }, function() {
	    //     $(".delete").remove();
	    // });

	    try{
		    div.mousewheel(function(event, delta) {

		        this.scrollLeft -= (delta * 30);
		        event.preventDefault();
		        scrollWheelTotal -= (delta * 30);
		        if (scrollWheelTotal > 890) {
		            scrollWheelTotal = 890
		        }
		        if (scrollWheelTotal < 0) {
		            scrollWheelTotal = 0
		        }
		        $("#scrollwheel").empty().append("div.mousewheel :" + scrollWheelTotal);
		    });
		}
		catch(e){
			//Fuck off type error, suck a dick.
		}

	})(jQuery);
}
/*
 * jQuery.styledSelect - <select> replacement plugin
 *
 * Copyright (c) 2009 Petr Stanicek (pixy@pixy.cz)
 * version 1.1, January 12, 2009
 * 
 *
 *	Change log:
 *	1.1 - Firefox 2 and older disabled due to wrong inline-block support.
 *
 
- usage: jQuery('#anyselect').styledSelect(options);
- options are optional 

CSS:	.select-replace: border, padding, background, font style
		.select-replace-cover: additional background
		select (the original element): font-size, width

Note:	Try to keep same size of original select and the replacing box - primary by adjusting
		font-sizes and padding, you'd better not to set height/width of those boxes.

Tip:	Use options {opacity:0.1} (or similar low value) to reveal the original select to fit the sizes
		while debugging. Don't forget to set it back to zero when you done.

Note:	If the original select is hidden while caling this function, you must trigger its resize handler
		after you show it first time, e.g.: jQuery('#myselect').trigger('resize')

*/


jQuery.fn.styledSelect = function(options) {
	var isFF2 = jQuery.browser.mozilla && jQuery.browser.version.indexOf('1.8.')==0;
	var prefs = {
		coverClass : 'select-replace-cover',
		innerClass : 'select-replace',
		adjustPosition : { top:0, left:0 },
		selectOpacity : 0
		}
	if (options) jQuery.extend(prefs,options);
	return this.each( function() {
		if (isFF2) return false;
		var selElm = jQuery(this);
		selElm.wrap('<span><'+'/span>');
		selElm.after('<span><'+'/span>');
		var selReplace = selElm.next();
		var selCover = selElm.parent();
		selElm.css({
			'opacity':prefs.selectOpacity,
			'visibility':'visible',
		/*	'position':'absolute', */
			'top':0,
			'left':0,
			'display':'inline',
			'z-index':1
			});
		selCover.addClass(prefs.coverClass).css({
			'display':'inline-block',
			'position':'relative',
			'top':prefs.adjustPosition.top,
			'left':prefs.adjustPosition.left,
			'z-index':0,
			'vertical-align':'middle',
			'text-align':'left'
			});
		selReplace.addClass(prefs.innerClass).css({
			'display':'block',
			'white-space':'nowrap'
			});

		selElm.bind('change',function() {
			jQuery(this).next().text(this.options[this.selectedIndex].text);
			}).bind('resize',function() {
			jQuery(this).parent().width( (jQuery(this).width())+'px' );
			});
		selElm.trigger('change').trigger('resize');
		});
	}
  //style contact form select
  try{
  $("form.wpcf7-form select").styledSelect();
}
catch(e){
	//Gotcha
}

//Will's fantastical JS -> PHP POST array converter

function serialize( mixed_value ) {
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") {
      val += ";";
  }
    return val;
}


