jQuery(document).ready(function($){
	resize_this_site();
	if( $('#current_slide_no') ){	
		$('#current_slide_no').val(1);
	}
});
window.onorientationchange = function(e) {
	resize_this_site();	
}

function resize_this_site() {
	if( $('#news_container').length ){
		// $('#news li').css({"width":$(window).width()});
		var t=setTimeout("update_news_width()",1000);
	}
	if( $('#tickercontainer').length ){
		var t=setTimeout("update_ticker_width()",1000);
	}
	if( $('#videos_container').length ){
		var t=setTimeout("update_video_width()",1000);
	}
	if( $('#apps-wrapper').length ){
		var t=setTimeout("update_apps_width()",1000);
	}
	if( $('#slides').length ){
		// var t=setTimeout("update_slide_width()",2000);
		var t=setTimeout("update_slide_width2()",1000);
	}
	if ( $('.content-slideshow').length ){
		var header_padding = $('.slide_container .header').css('padding-top');
		header_padding = header_padding.substring(0, header_padding.length-2)
		var shift_buttons = ($('.slide_container .header').height() + 2 * header_padding + (($('.thumb').height()/2) - 20) ) + "px";
		$('.pager_page').css({"top": shift_buttons });
	}
}
var loadedSlides = 0;

/**
 * handlePagerEvent
 * 
 * Handles swipe and click/tap events for slider elements 
 */
 
function handlePagerEvent(event, direction) {
	if ($(this).hasClass('pager_button')) {
		// Bottom circle pager buttons
		var type = event.type;
		var pager = $(this).parents('.pager');
		var parentObj = pager.prevAll('.section_container').children('.gallery-wrapper:first').children('.slider_section');
	} else if ($(this).hasClass('slider_section') || $(this).hasClass('')) {
		// Swipe event
		var type = direction;
		var parentObj = this;
		var pager = $(this).parent().parent().nextAll('.pager:first');
	} else if (this === window || $(this).hasClass('pager_page')) {
		// Slideshow Page events
		var elem = event.currentTarget;

		if ($(elem).parent('.slide_container').length == 0) {
			// Page Left/Right - Homepage
			var type = 'click';
			var pager = null;
			var parentObj = $(elem).parent('.section_container').children('.gallery-wrapper').children('.slider_section');
		} else if ($(elem).hasClass('slides')) {
			// Page Left/Right - Slideshow
			type = 'click';
			var pager = null;
			var parentObj = $(elem).nextAll('.gallery-wrapper').children('#slides');
		}
	}

	var nextPos = 0; // where to move to
	var childrenObj = parentObj.children(); // child element sections	
	var elemPos = parentObj.css('left') == 'auto' ? 0 : parseInt(parentObj.css('left')); // current position	
	var childCount = parseInt(childrenObj.length); // number of sections
	var childWidth = $(window).width();   // width of sections
	var maxWidth = (childCount * childWidth) - childWidth; // total width of sections
	var currentId = elemPos == 0 ? 0 : Math.abs(elemPos)/childWidth; /// current position pager id;
		
	var superOffset = parentObj.offset();
	var superElemPos = superOffset.left == 0 ? 0 : parseInt(superOffset.left); // current position
	var superCurrentId = superElemPos / $(window).width();
	
	// reset if something is off
	if (elemPos % childWidth !== 0) elemPos = 0;

	// Get next position based on event type and current position
	switch(type) {
		case 'left':
			nextPos = superElemPos - 100/*childWidth*/;
			
			if (superCurrentId != -(childCount-1)){
				superCurrentId--;
			}

			if (Math.abs(nextPos) > maxWidth) return false;
			break;
		case 'right':
			nextPos = superElemPos + 100 /*childWidth*/;
			
			if (superCurrentId != 0){
				superCurrentId++;
			}

			if (nextPos > 0) return false;
			break;
		case 'click':
			if (pager !== null) {
				// Button Pager Nav
				var pagerId = parseInt(event.currentTarget.id.match(/\d+/)); // position we're moving to
				superCurrentId = -pagerId;
			} else {
				// Page Left/Right buttons
					
				if ($(elem).hasClass('right')) {
					nextPos = superElemPos - 100 /* childWidth */;
					
					if (superCurrentId != -(childCount-1)){
						superCurrentId--;
					}
					if (Math.abs(nextPos) > maxWidth) return false;
				} else {
					nextPos = superElemPos + 100 /* childWidth */;
					
					if (superCurrentId != 0){
						superCurrentId++;
					}
					if (nextPos > 0) return false;
				}
				//check if we actually have a pager
				pager = $(elem).parent().nextAll('.pager:first');
				if (pager.length == 0) pager = null;
			}
			break;
	}

	// new pager position id
	var nextId = nextPos == 0 ? 0 : Math.abs(nextPos) / childWidth;

	// Change pager buttons to current page
	if(pager) {
		pager.children().children().each(function(i){
			if (i == Math.abs(superCurrentId)) {
				$(this).addClass('active');
			} else {
				$(this).removeClass('active');
			}
		});
	}
	nextPos = superCurrentId * 100;

	// Animate
	$(parentObj).animate({left: nextPos + "%"}, {duration: 500, easing: "swing"});
	
	var last_slide = '';
	if( -(superCurrentId - 1) == childCount){
		last_slide = 'last-slide';
	} else if ( -(superCurrentId - 1) == 1 ) {
		last_slide = 'first-slide';
	} else {
		last_slide = '';
	}
	$(parentObj).parents('.section_container').removeClass('first-slide').removeClass('last-slide').addClass(last_slide);
	return false;
}
// Slideshow page event handler
function slide(event, direction) {
	event.stopPropagation(); // stop the bubbly
	
	if ($(this).hasClass('pager_page')) {
		// Pager button
		var type = event.type;
	} else {
		// Swipe event
		var type = direction;
	}
	var currentSlide = parseInt($('#current_slide_no').val());
	var slideCount = parseInt($('#slide_count').val());
	if (type == 'left' || (type == 'click' && $(event.currentTarget).hasClass('right'))) {
		var nextSlide = currentSlide + 1;

		if (nextSlide > loadedSlides && nextSlide <= slideCount) {
			// expand width of #slide by 320 to fit new slide
			// $('#slides').css({'width': (loadedSlides + 1) * 100 + '%' }); moved below
			// $('#slides').css('width', function(index, value){return parseInt(value)+ $(window).width() });
			// load new slide via ajax
			$.ajax({
				url: '',
				data: {slide: nextSlide},
				dataType: 'html',
				method: 'POST',
				success: function(new_slide) {
					// iterate loaded slide count
					loadedSlides++;
					$('#slides').css({'width': (loadedSlides) * 100 + '%' });
					// iterate current slide number
						$('#current_slide_no').val(nextSlide);
					//put new slide into expanded space
					$('#slides').append(new_slide);
					
					$('.slide').each(function() {
						$(this).css({'width': 100/loadedSlides + '%'});
					});
					
					
					
					//pass on to pager event to scroll
					handlePagerEvent(event);
				}
			});
			//var t=setTimeout($('#slides').css({'width': (loadedSlides + 1) * 100 + '%' }),1000);
			// $('#slides').css({'width': (loadedSlides + 1) * 100 + '%' });
		} else {
					if( $('#current_slide_no').val() != slideCount ){
						$('#current_slide_no').val(nextSlide);
					}
			
			//pass on to pager event to scroll
			handlePagerEvent(event);
		}
	} else {
		var nextSlide = currentSlide - 1;

		if (nextSlide > 0) {
			$('#current_slide_no').val(nextSlide);
		}
		
		//pass on to pager event to scroll
		handlePagerEvent(event);
	}
	var slides_slide = '';
	if ( currentSlide == 1){
		slides_slide = 'first-slide'
	} else if (currentSlide == slideCount){
		slides_slide = 'last-slide'
	} else {
		slides_slide = ''
	}
	$(this).parents('.slide_container').removeClass('first-slide').removeClass('last-slide').addClass(slides_slide);
	console.log('currentSlide: ' + currentSlide + ' | slideCount: ' + slideCount + ' | slides_slide: ' + slides_slide);
}

function update_ticker_width(){
	var ticker_width = 0;
	$('#ticker li').each(function(index) {
		ticker_width += $(this).width() + 45;
  });
	$('ul#ticker').css({"width":ticker_width});
}
function update_news_width(){
	$('#news li').each(function(){
		$(this).css({"width": $(window).width()});
	});
	$('#news li p').each(function(){
		$(this).css({"font-size":'1em'});
	});
}
function update_apps_width(){
	$('#apps-wrapper ul#apps').css({"width": 100 * $('#apps-wrapper ul#apps > #app_row').size() + '%' })
	$('#apps-wrapper #app_row').each(function(){
		$(this).css({"width": 100/$('#apps-wrapper ul#apps > #app_row').size() + '%'});
	});
}

function update_video_width(){
	var ua = navigator.userAgent.toLowerCase();
	var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
	
	var NUMBER_OF_VIDEOS = 3;
	
	var old_width = $('.video_cell').width();
	var current_left = parseInt($('#videos').css('left'));
	var current_pos = Math.abs(current_left) / old_width;
	var new_left = 0 - (current_pos * $(window).width());
	
	$('#videos').css({"width": NUMBER_OF_VIDEOS * $(window).width() });
	$(".video_cell").each(function(i){
		$('.video_cell').css({"width": $(window).width()});
	});
	$('#videos_container .gallery-wrapper').css({"height": $("#videos_container .gallery-wrapper #videos .video_cell").height() });
	
	if(isAndroid) {
	}
	
	// $('#videos').animate({left: new_left}, {duration: 500, easing: "swing"});
}

function update_slide_width3() {
	
}
function update_slide_width2() {
	// currently not in use
	$('#slides').css({'width': (loadedSlides) * 100 + '%' });
	// $('#slides li').css({'width': 100 / loadedSlides + '%' });
}

function update_slide_width() {
	// currently not in use
	var NUMBER_OF_SLIDES = $('#slides').children('.slide').length;
	
	var old_width = $('.slide').width();
	var current_left = parseInt($('#slides').css('left'));
	var current_pos = Math.abs(current_left) / old_width;
	var new_left = 0 - (current_pos * $(window).width());
	
	$('#slides').css({"width": NUMBER_OF_SLIDES * 100 + '%'/*$(window).width()*/ });
	$('.slide').each(function(i){
		$(this).css({"width": 100 / NUMBER_OF_SLIDES + '%'});
		// $(this).css({"width": $(window).width() });
	});
	$('#slide_container .gallery-wrapper').css({"height": $('.slide').height() });
	$('#slides').animate({left: new_left}, {duration: 500, easing: "swing"});
}

// Homepage videos section youtube feed
function getVideos() {
	var ua = navigator.userAgent.toLowerCase();
	var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
	
	var number_of_videos = 3;
	if(isAndroid) {
		var number_of_videos = 1;
	}
	$('#videos').css({"width":number_of_videos * $(window).width() });
	
	$.ajax({
		url: 'http://gdata.youtube.com/feeds/api/users/Agriculturecom/uploads',
		data: {
			v: 2,
			alt: 'jsonc',
			'max-results': number_of_videos
		},
		type: 'GET',
		dataType: 'json',
		success: function(gdata) {
			var videos = gdata.data.items;
			var frames = '';
			
			if(isAndroid) {
				for(var i=0; i<1; i++) {
					var title = videos[i].title;
					var url = videos[i].player['default'];
					var id = videos[i].id;
					var media_width = $(window).width();
					frames += '<li class="video_cell">\n';
					frames += '<p class="video_title">' + title + '</p>\n';
					frames += '<div class="video">\n';
					frames += '<iframe src="http://www.youtube.com/embed/' + id + '?rel=0&showinfo=0&wmode=transparent" frameborder="0" style="width:100%; height:auto;"></iframe>';
					frames += '</div>\n';
					frames += '</li>\n';
				}
			} else {
				for(i in videos) {
					var title = videos[i].title;
					var url = videos[i].player['default'];
					var id = videos[i].id;
					var media_width = $(window).width();
					frames += '<li class="video_cell">\n';
					frames += '<p class="video_title">' + title + '</p>\n';
					frames += '<div class="video">\n';
					frames += '<iframe src="http://www.youtube.com/embed/' + id + '?rel=0&showinfo=0&wmode=transparent" frameborder="0" style="width:100%; height:100%;"></iframe>';
					frames += '</div>\n';
					frames += '</li>\n';
				}
			}
			$('#videos').append(frames);
			loadedSlides = number_of_videos;
		}
	});
	var t=setTimeout("update_video_width()",2000);
}

function getMobileTalkData(o) {
	$.data(o.summary_el, "ui", o);
	$.ajax(
		{
			url:'/home/talkajax',
			data: {
				boardid: o.boardid
			},
			type: 'POST',
			complete: function (x,s) {
				var ui = $.data(o.summary_el, "ui");
				var data = $.parseJSON(x.responseText);
				
				if(data) {
					ui.summary_el.html(data.summary);
					ui.loader_el.hide();
				}			
			}
			
		}
	);
}

// Homepage commodities ticker
function getTicker() {
	$.ajax({
		url: '/home/ticker',
		type: 'GET',
		dataType: 'JSON',
		success: function(data) {
			var list = '';
			
			if (typeof data === 'object') {
				for (i in data) {
					var last = parseFloat(data[i]['Last']);
					var change = parseFloat(data[i]['Change']);
					var direction = change >= 0 ? 'up' : 'down';

					last = last.toFixed(2);
					change = change.toFixed(2);

					list += '<li>' + data[i].Commodity + ' ' + last;
					list += '<span class="' + direction + '">';
					if (direction == 'up') list += '+'; // add plus sign
					list += change;
					list += '</span></li>\n';
				}
				$('#ticker').append(list);
			}
		}
	});
	var t=setTimeout("update_ticker_width()",2000);
}

// Polls form submit
function vote(obj){
	params = $("#poll_form").serialize();
	
	if (!obj && params.indexOf('option')==-1) {
		$("#poll_form .poll_error").html('Please choose an option:');
	} else {
		$("#poll_form .poll_error").html('');
		$("#poll_form").load("/home/vote?option="+$("#option").val(),'', function(){/* refreshAdTags(); */});    
	}
}

// BEGIN: handle Portrait to Landscape shift bug on iOs
	if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
		var viewportmeta = document.querySelector('meta[name="viewport"]');
		if (viewportmeta) {
			viewportmeta.content = 'width=device-width, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0, target-densityDpi=device-dpi';
		}
	}
// END: handle Portrait to Landscape shift bug on iOs

