/*
 * Recipe vars
 */
var recipes = null;
var recipeTimer = null;
/* Events */
var mapSettings = {};
var eventImages = [];
var eiPos = 0;

/* homepage promos */
var promoImages = [];
var prPos = 0;

$(document).ready(function (){
	//mini-bites entry char count - count down from 140
	
	var pageId = $('body').attr('id');
	
	//for events, that could be anywhere...
	mapInit(); 
	imageInit(); 
	galleryInit();
	
	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 );
	*/
	
	$('#flash-promo').imgTransition({transitionEnd: transEndCallback, initialised: startCallback, imgList: promoImages, idx: prPos});
}


/*
 * Callback triggered after transition has been initialised
 * this is mainly to work around an issue with IE6
 */
function startCallback(container){
	//sorry, got to check for IE6
	if($.browser.msie && $.browser.version == 6){
		//add a click event to all the images - so we hit one of them
		container.children('img').bind('click', triggerLink);
	}
}

/*
 * callback function to be invoked after the transition
 * the container is passed back and the current position in the image array
 */
function transEndCallback(container, idx){
	if(promoImages[idx].link){
		if(container.parent('a').length > 0){
			container.parent('a').attr('href', promoImages[idx].link);
		} else {
			container.wrap('<a class="promoLink" href="' + promoImages[idx].link + '"></a>');
		}
		//sorry, got to check for IE6
		if($.browser.msie && $.browser.version == 6){
			//add a click event to all the images - so we hit one of them
			container.children('img').bind('click', triggerLink);
		}
		
	} else {
		//if there is a link - remove it
		if(container.parent('a').length > 0){
			container.unwrap();
			//sorry, got to check for IE6
			if($.browser.msie && $.browser.version == 6){
				//add a click event to all the images - so we hit one of them
				container.children('img').unbind('click', triggerLink);
			}
		}
	}
}

function triggerLink(){
	window.location.href = $('.promoLink').attr('href');
}

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 );
		}
	}
}

/* event functions */

function imageInit(){
	if($('#eventImage').length > 0){
		$('#eventImage').imgTransition({idx: eiPos, imgList: eventImages});
	}
}

function mapInit(){
	if(mapSettings.mapType){
		var coords = new google.maps.LatLng(mapSettings.latitude, mapSettings.longitude);
		var mapType;
		switch(mapSettings.mapType){
			case 'map':
				mapType = google.maps.MapTypeId.ROADMAP;
				break;
			case 'terrain':
				mapType = google.maps.MapTypeId.TERRAIN;
				break;
			case 'satellite':
				//fallthrough
			default:
				mapType = google.maps.MapTypeId.SATELLITE;
				break;
		}
		var opts = {
				zoom: parseInt(mapSettings.zoom),
				center: coords,
				mapTypeId: mapType
		};
	
		var map = new google.maps.Map(document.getElementById('mapArea'), opts);
	
		//add pointer
		var marker = new google.maps.Marker({
			position: coords,
			map: map	
		});
	
		//add overlay
		var infoWin = new google.maps.InfoWindow({
			content: '<div id="overlayContainer">' + mapSettings.content + '</div>',
			maxWidth: 300
		});
	
		//add overlay to marker
		google.maps.event.addListener(marker, 'click', function(){infoWin.open(map, marker);});
	}
}

function galleryInit(){
	if($('#carousel').length > 0){
		$('#carousel').jcarousel({
			wrap: 'circular',
			scroll: 1,
			animation: 500,
			initCallback: setupImageCount,
			itemFirstInCallback: imageChanged
		});
	}
}

/* Gallery callbacks */
function setupImageCount(carousel, state){
	$('.imageCount').html('1 / ' + carousel.size());
}

function imageChanged(carousel, item, idx, state){
	var total = carousel.size();
	//work out the actual idx
	//first check if we've gone backwards
	if(idx <= 0){
		idx *= -1;
		if(idx < total){
			idx = total - idx;
		} else {
			idx = total - (idx%total);
		}
	}
	
	if(idx > total){
		idx = idx % total;
	}
	
	if (idx == 0){
		idx = total;
	}
		
	$('.imageCount').html(idx + ' / ' + total);
}
