/*
 * Recipe vars
 */
var recipes = null;
var recipeTimer = null;

$(document).ready(function (){
	//mini-bites entry char count - count down from 140
	
	var pageId = $('body').attr('id');
	
	switch(pageId){
		case 'home':
			homepageInit();
		break;
		
		case 'article-print':
			articlePrintInit();
		break;
		
		default:
	}
	
	 //
	 setupReviewPagination();
	 setupRecipeSlideshow();
	 setupRecipePrint();
	 setupFaqs();
	 setupCommentReporting();
	 setupTins();
	//set up link to MasterCard SecureCard info
	setupMcScLink();
	
	if( $('#miniMomentsForm').length ) setupMiniMomentsForm();
});

function homepageInit(){
	
	var params = {
		wmode: 'transparent'
	};
	
	swfobject.embedSWF('/media/site/swf/ryvitaHeader.swf', 'flash-promo', '763', '382', '8.0.0', '/media/site/swf/expressInstall.swf', null, params );
}

function setupFaqs(){
	// hides the slickbox as soon as the DOM is ready
	// (a little sooner than page load)
	 $('.answers').hide();
	// shows the slickbox on clicking the noted link  
	 $('.question').click(function() {
		  $(this).addClass('opened');
		  $(this).next('div').addClass('opened');
	   $(this).next('div').toggle('slow');
	   return false;
	 });
}


function setupReviewPagination(){
	$('#comments #pagination a').click(function (){
		//get the current page
		link = this.href.split(/\?/);
		var page = getParam(link[1], "page");
		var id = getParam(link[1], "id");
		//alert("page = "+page + "id = "+id);
		if(page){
			$.ajax({
				async: false,
				url: '/media/site/helpers/comment.php?page=' + page + '&id=' + id,
				type: 'get',
				dataType: 'json',
				error: function (){
					alert('oops');
				},
				success: function (result){
					//update pagination
					$('#comments').replaceWith(result.html);
					setupReviewPagination();
					setupCommentReporting();
					return false;
				}
			});
		}
		return false;
	});
}

function getParam(query, paramName){
	var param = '';
	if(query){
		var params = query.split('&');
		for (i = 0; i < params.length; i++) {
			var p = params[i].split("=");
			if (p[0] == paramName) {
				param = p[1];
				break;
			}
		}
	}
  return param;
}

function setupRecipeSlideshow(){
	$('#slideshow .controls p').show();
	$('#slideshow .controls .prev').click(function (){
		return nextClick();
	});
	
	$('#slideshow .controls .next').click(function (){
		return prevClick();
	});
	
	//start a timer if the slideshow is available.
	if(document.getElementById('slideshow')){
			recipeTimer = setInterval("nextClick();", 10000);
	}
}

function nextClick(){
	updateSlide(getNextSlide());
	return false;
}

function prevClick(){
	updateSlide(getPrevSlide());
	return false;
}

function getNextSlide(){
	var next;
	var id = getCurrent();
	var len = recipes.length;
	if(id >= (len-1)){
		next = 0;
	} else {
		next = id+1;
	}
	return next;
}

function getPrevSlide(){
	var prev;
	var id = getCurrent();
	var len = recipes.length;
	if(id == 0){
		prev = len-1;
	} else {
		prev = id-1;
	}
	return prev;
}

function getCurrent(){
	var tmp = $('#slideshow h3').attr('id').split('_');
	return parseInt(tmp[1]);
}

function updateSlide(current){
	var data = recipes[current];
	$('#slideshow h3').html(data.name);
	$('#slideshow h3').attr('id', 'slide_' + current);
	$('#slideshow img').attr('src', data.image);
	$('#slideshow > p:first').html(data.description);
	$('#slideshow .controls .try').attr('href', data.url);
	$('#slideshow .recipe-link').attr('href', data.url);
}

function setupRecipePrint(){
	if($('body').attr('id') == 'recipe-print'){
		window.print();
		window.close();
	}
}

function articlePrintInit(){
	window.print();
	window.close();
}

function setupCommentReporting(){
	$('#comments .report').click(function (){
		link = this.href.split(/\?/);
		var cid = getParam(link[1],'reportId');
		var oid = getParam(link[1],'oid');
		$.ajax({
			async: false,
			url: '/media/site/helpers/comment.php?reportId=' + cid + '&oid=' + oid,
			dataType: 'json',
			error: function (){
				alert('We have had a problem reporting the comment. Please try again in a few moments.');
				return false;
			},
			success: function (result){
				if(result.success){
					launchReportOverlay(result.html);
				}
				return false;
			}
		});
		return false;
	});
}

function launchReportOverlay(html){
	$('#reportOverlay #form').html(html);
	// select the overlay element - and "make it an overlay"
    $("#reportOverlay").overlay({
    	top: 60,
    	closeOnClick: false,
    	api: true
    }).load();
    setupReportForm();
}

function setupReportForm(){
	$('#reportOverlay #reportCommentForm').submit(function (){
		//gather inputs
		var report = $('#reportOverlay #reportCommentForm #report').val();
		var cid = $('#reportOverlay #reportCommentForm #commentId').val();
		var captcha = $('#reportCommentForm input[name="captchaText"]').val();
		$.ajax({
			async: false,
			url: '/media/site/helpers/comment.php?reportId=' + escape(cid),
			data: 'report=' + escape(report) + '&captchaText=' + escape(captcha),
			type: 'post',
			dataType: 'json',
			error: function (){
				alert('We\'ve experienced a problem submitting your report. Please try again in a few moments');
				return false;
			},
			success: function (result){
				if(result.success){
					$('#reportOverlay #form form').html('<h4>Report a comment</h4><p class="result">' + result.html + '</p>');
				} else {
					$('#reportOverlay #form').html(result.html);
					setupReportForm(); //we will need to resubmit
				}
				return false;
			}
		});
		return false;
	});
	return false;
}

function setupTins(){
	if(document.getElementById('tins-landing')){
		//set initial status for delivery address
		if($('#separate-delivery-address').attr('checked')){
			$('#delivery-address').show();
		} else {
			$('#delivery-address').hide();
		}
		//set click handler
		$('#separate-delivery-address').click(function (){
			if(this.checked){
				$('#delivery-address').slideDown('fast');
			} else {
				$('#delivery-address').slideUp('fast');
			}
		});
		$('select[id^="quantity-"]').change(function (){
			updateSubTotal();
		});
	
		// call once to init
		updateSubTotal();
	}
}

function updateSubTotal() {
	var total = 0;
	
	$('select[id^="quantity-"]').each(function(i, val){
		total += parseInt(this.value);		
	});
	var grandtotal = (total * unitcost);
	if(grandtotal > 0){
		grandtotal += parseFloat(pandp);
	}
	$('#subtotal').html(grandtotal.toFixed(2));
}

function setupMcScLink(){
	$('#mc-info').click(function (){
		var url = this.href;
		//load overlay
		$('#reportOverlay').addClass('mc-info-window');
		$("#reportOverlay").overlay({
	    	top: 60,
	    	closeOnClick: false,
	    	api: true,
	    	onClose: function (){$('#mc-info-frame').remove();}
	    }).load();
		
		var iframe = document.createElement('iframe');
		iframe.id="mc-info-frame";
		iframe.scrolling = 'no';
		$('#reportOverlay #form')[0].appendChild(iframe);
		iframe.src = url;
		
		return false;
	});
}

function setupMiniMomentsForm(){
	
	var maxLength = 140;
		
	var momentForm = $('#miniMomentsForm');
	var momentLi = $('.moment:eq(0)', momentForm);
	var momentLabel = $('label:eq(0)', momentLi);
	var momentTxt = $('textarea:eq(0)', momentLi);
	
	//check if we already have copy and reduce maxLength accordingly
	if(momentTxt.val().length > 0){
		maxLength = maxLength - momentTxt.val().length;
	}
	
	momentLabel.append('<span class="count">'+maxLength+'</span>');
	
	var momentCount = $('.count:eq(0)', momentLabel);
	
	momentTxt.bind('keyup', keyUpEvent);
	
	function keyUpEvent(e){
		var el = $(e.target);
		
		var v = el.val();
				
		if( v.length > maxLength ){
			el.val( v.substr(0, maxLength) );
			momentCount.text('0');
			
		} else {
			momentCount.text( maxLength - v.length );
		}
	}
}