var timer, waitTimer, applyModeTimer;
var content, canL, imgL, imgR, vdd, viewL, viewR, zoomer, width, height;
var animating = true, zoom = 1, zoomH = 1;
var viewDragging, viewMode;
//viewDragging: true=paused
//viewMode: 0=mono,1=red/blue,2=yellow/blue,3=parallel,4=crosseye
var viewBounce = 1, viewDisparity = 5;
var viewX = 0, viewY = 0;
var sideCrop = 20;

function makeRedCyanAnaglyph()
{
	var canvas = document.getElementsByTagName('canvas')[0];
	var w = (width+sideCrop)*11, h = height, wvd = (width+sideCrop)*viewDisparity;
	canvas.width = w;
	canvas.height = h;
	var cc = canvas.getContext('2d');
	cc.drawImage(imgL, 0, 0, w, h);
	var cd;
	try { cd = cc.getImageData(0, 0, w, h); } catch(e)
	{
	  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	  cd = cc.getImageData(0, 0, w, h);
	}
	var k = w - wvd;
	var s = wvd*4;
	var l = 0, y, x;
	for (y=height+1; --y; l+=s) for (x=k+1; --x; l+=4)
	{
	  cd.data[l] = (cd.data[l]*8+cd.data[l+1]*5+cd.data[l+2]*3)>>4;
	  cd.data[l+1] = cd.data[l+s+1];
	  cd.data[l+2] = cd.data[l+s+2];
	}
	cc.putImageData(cd, 0, 0);
}

function makeYellowBlueAnaglyph()
{
	var canvas = document.getElementsByTagName('canvas')[0];
	var w = (width+sideCrop)*11, h = height, wvd = (width+sideCrop)*viewDisparity;
	canvas.width = w;
	canvas.height = h;
	var cc = canvas.getContext('2d');
	cc.drawImage(imgL, 0, 0, w, h);
	var cd;
	try { cd = cc.getImageData(0, 0, w, h); } catch(e)
	{
	  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	  cd = cc.getImageData(0, 0, w, h);
	}
	var k = w - wvd;
	var s = wvd*4;
	var l = 0, y, x;
	for (y=height+1; --y; l+=s) for (x=k+1; --x; l+=4)
	{
	  cd.data[l] = (cd.data[l]*8+cd.data[l+1]*5+cd.data[l+2]*3)>>4;
	  cd.data[l+2] = cd.data[l+s+2];
	}
	cc.putImageData(cd, 0, 0);
}

function startAnimation()
{
	$('#preloader').hide();
	$('#preloader2').hide();
	$('#leftThumb').hide();
	$('#rightThumb').hide();
	$("#leftPlayImg").hide();
	$("#rightPlayImg").hide();
	$("#leftPauseImg").hide();
	$("#rightPauseImg").hide();
	width = Math.round(imgL.clientWidth/11) - 2*sideCrop;
	height = imgL.clientHeight;
	if (height != 0) vdd.style.height = height*zoomH+'px';
	viewL.style.width = viewR.style.width = width+'px';
	viewL.style.height = viewR.style.height = height+'px';

	applyMode();

	if (width > 10 && height > 10)
	{
		animating = true;
  		animate();
	}
}

function waitForImages()
{
	clearTimeout(waitTimer);
	if (!imgL.complete || !imgR.complete)
		waitTimer = setTimeout("waitForImages();", 100);
	else
		startAnimation();
}

function toggleZoom()
{
	zoom = (zoom == 1 ? 1.5 : (zoom == 1.5 ? 2 : 1)); //toggle 1<->2
	applyMode();
}

function setView(target)
{
	animating = false;
	clearTimeout(timer);
	content = document.getElementById("content");
	canL = document.getElementById("canL");
	imgL = document.getElementById("imgL");
	imgR = document.getElementById("imgR");
	vdd = document.getElementById("vdd");
	zoomer = document.getElementById("zoomer");
	viewL = document.getElementById("viewL");
	viewR = document.getElementById("viewR");
	if (imgL == null || imgR == null) return;
	imgL.src = imgR.src = target;
	waitForImages();
}

function applyMode()
{
	clearTimeout(applyModeTimer);
	applyModeTimer = setTimeout("applyMode2()", 100);
}

function applyMode2()
{
	if (viewMode == 3 || viewMode == 4)
	{
		viewL.style.zoom = viewR.style.zoom = 1;
		viewL.style.MozTransform=viewR.style.MozTransform = 'scale('+1+')';
		viewL.style.left = '0px';
		viewR.style.left = '4px';
		viewR.style.display = 'block';
		zoomer.style.zoom = zoom;
		zoomer.style.MozTransform='scale('+zoom+')';
		zoomer.style.MozTransformOrigin='top left';
		zoomH = 1;
	}
	else
	{
		var cw = 836;//content.style.width;
		viewL.style.zoom = viewR.style.zoom = zoom;
		viewL.style.left = ((cw - zoom*width)*0.5)+'px';
		viewR.style.display = 'none';
		viewL.style.MozTransform=viewR.style.MozTransform = 'scale('+zoom+')';
		viewL.style.MozTransformOrigin=viewR.style.MozTransformOrigin = 'top left';
		zoomer.style.zoom = 1;
		zoomer.style.MozTransform='scale(1)';
		zoomH = zoom;
	}
	if (height != 0) vdd.style.height = height*zoomH+'px';
	viewL.style.width = viewR.style.width = width+'px';
	viewL.style.height = viewR.style.height = height+'px';
	//viewL.style.styleFloat = viewL.style.cssFloat = (viewMode <= 2 ? "none" : "auto");
	if (viewMode == 1) makeRedCyanAnaglyph();
	else if (viewMode == 2) makeYellowBlueAnaglyph();
	else
	{
		var canvas = document.getElementsByTagName('canvas')[0];
		canvas.width = 0;
		canvas.height = 0;
	}
}

function setMode(newMode)
{
	viewMode = newMode;
	// set view mode inside cookie for 30 days
	applyMode();
	updateActiveButton(newMode);

	// cookie is for not-logged-in user
	setCookie('vm', newMode, 30);
	//user logged in
	$.ajax({
		url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/view-mode/' + newMode,
		success: function(resp){
		}
	});

}

function animate()
{
	clearTimeout(timer);
	if (!animating) return;
	var timeout = 50;
	var maxX = (viewMode == 0 ? 10 : 10 - viewDisparity);
	if (!viewDragging)
	{
		viewX += viewBounce;
		timeout = (150 - 3 * viewX * (maxX - viewX));
	}
	if (viewX <= 0) { viewX = 0; viewBounce = 1; }
	if (viewX >= maxX) { viewX = maxX; viewBounce = -1; }
	var viewXR = viewX + viewDisparity;
	var tL = (viewMode <= 3 ? ((viewMode == 1 || viewMode == 2) ? canL : imgL) : imgR);
	var tR = (viewMode <= 3 ? imgR : imgL);
	tL.style.left = (viewY*(viewX-5))-Math.round(tL.clientWidth/11)*viewX-sideCrop+'px';
	tR.style.left = (viewY*(viewXR-5))-Math.round(tR.clientWidth/11)*viewXR-sideCrop+'px';
	if (animating) timer = setTimeout("animate();", timeout);
}

function stopAnimation()
{
	if (viewDragging) return; // do nothing
	showPlayControls();
	saveControls('still');
	viewDragging = true;
	$("#slider").attr('moveTo', viewX);
	$("#slider_duplicate").attr('moveTo', viewX);
	return false; /* prevent selection */
}

function setHorizontal(inValue)
{
	viewX = Math.round(inValue);
}

function setDepth(inValue)
{
	viewDisparity = Math.round(inValue);
	applyMode(); // this is necessary for anaglyph modes
}

function goAnimate()
{
	if (!viewDragging) return; // do nothing
	showPauseControls();
	saveControls('animated');
	viewDragging = false;
	animating = true;
    animate();
}

function updateActiveButton(mode)
{
	$("#leftPlayImg").hide();
	$("#rightPlayImg").hide();
	$("#leftPauseImg").hide();
	$("#rightPauseImg").hide();
	
	for (i = 0; i <= 4; i ++)
	{
		$('#view_mode_' + i).removeClass('active');
		$('#view_mode_' + i).removeClass('first');
		$('#view_mode_' + i).removeClass('middle');
		$('#view_mode_' + i).removeClass('last');
	}
	$('#view_mode_' + mode).addClass('active');
	if (mode == 0)
	{
		$('#view_mode_' + mode).addClass('first');
	}
	else if (mode == 4)
	{
		$('#view_mode_' + mode).addClass('last');
	}
	else
	{
		$('#view_mode_' + mode).addClass('middle');
	}
	if (mode == 0)
	{
		$('#sliderDepthWrap').hide();
	}
	else
	{
		$('#sliderDepthWrap').show();
	}
	if (mode == 4 || mode == 3)
	{
		$('#viewR').show();
		$('.sliderWrap').addClass("sliderWrapSmall");
		$('.halfSlideRight').show();
		$('.halfSlideLeft').css("width", "416px");
	}
	else
	{
		$('#viewR').hide();
		$('.sliderWrap').removeClass("sliderWrapSmall");
		$('.halfSlideRight').hide();
		$('.halfSlideLeft').css("width", "830px");
	}
}

// cookie functions

// set cookie
function setCookie(cookie_name,value,expiredays)
{
	var exdate = new Date(new Date().getTime()+1000*60*60*24*expiredays);
	document.cookie = cookie_name+ "=" +escape(value)+ ";path=/;expires="+exdate.toGMTString();
}

//get cookie
function getCookie(cookie_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(cookie_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + cookie_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}


// save controls used by user
function saveControls(control_type)
{
	// cookie is for not-logged-in user
	setCookie('vc', (control_type == 'still'), 30);
	//user logged in
	$.ajax({
		url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/user-controls/' + control_type,
		success: function(resp){
		}
	});
}

this.makeTooltip = function(tooltip, target){
	//determine popup's distance from the cursor
		xOffset = 10;
		yOffset = 30;

	target.hover(function(e){
		this.title = "";
		tooltip
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		tooltip.fadeOut("fast");
    });
	
	target.mousemove(function(e){
		tooltip
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

this.showPlayControls = function(){
	$('#playBtn').show();
	$('#pauseBtn').hide();
	$('#playBtn_duplicate').show();
	$('#pauseBtn_duplicate').hide();
	
	$("#leftPauseImg").fadeIn(200);
	$("#rightPauseImg").fadeIn(200);
	$("#leftPauseImg").fadeOut(200);
	$("#rightPauseImg").fadeOut(200);
};

this.showPauseControls = function(){
	$('#playBtn').hide();
	$('#pauseBtn').show();
	$('#playBtn_duplicate').hide();
	$('#pauseBtn_duplicate').show();
	
	$("#leftPlayImg").fadeIn(200);
	$("#rightPlayImg").fadeIn(200);
	$("#leftPlayImg").fadeOut(200);
	$("#rightPlayImg").fadeOut(200);
};

$(document).ready(function() 
{
	
	// the start-up view
	if ($('#photoSrc').length)
	{
		viewDragging = $('#playVar').val(), viewMode = $('#modeVar').val();
		viewDragging = (viewDragging == 'still' ? true : (viewDragging == 'animated' ? false : (getCookie('vc') == 'true')));
		if (viewMode == '') viewMode = getCookie('vm');
		if (viewMode == '') viewMode = 0;
		setCookie('vc', viewDragging, 30);
		setCookie('vm', viewMode, 30);
		updateActiveButton(viewMode);
		setView($('#photoSrc').val());
	}

	makeTooltip($("#dfp_tooltip"), $("#dont_feature_photo"));
	makeTooltip($("#dpp_tooltip"), $("#dont_print_photo"));
	
	$('#flag_photo').click(function(){
		if (confirm('Are you sure?'))
		{
			$.ajax({
				url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/flag-photo/' + $('#js_user_ident').val() + '/' + $('#js_photo_ident').val(),
				cache: false,
				success: function(response){
					if (response == 1)
					{
						$('#flag_photo').removeClass('flagPhoto');
						$('#flag_photo').addClass('flagPhotoClicked');
						alert(_s.js.thanks_flagged);
					}
				}
			});
		}
		return false;
	});

	$('#feature_photo').click(function(){
		$.ajax({
			url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/feature-photo/' + $('#js_user_ident').val() + '/' + $('#js_photo_ident').val(),
			cache: false,
			success: function(response){
				if (response == 1)
				{
					$('#feature_photo').parent().removeClass('orangeBtn');
					$('#feature_photo').parent().addClass('orangeBtnClicked');
					alert(_s.js.thanks_featured);
				}
			}
		});
		return false;
	});

	$('#buy_photo').click(function(){
		$.ajax({
			url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/buy-photo/' + $('#js_user_ident').val() + '/' + $('#js_photo_ident').val(),
			cache: false,
			success: function(response){
				if (response == 1)
				{
					$('#feature_photo').parent().removeClass('orangeBtn');
					$('#feature_photo').parent().addClass('orangeBtnClicked');
					alert(_s.js.thanks_bought);
				}
			}
		});
		return false;
	});


	$('#feature_tree').click(function(){
		$.ajax({
			url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/feature-tree/' + $('#js_user_ident').val() + '/' + $('#js_photo_ident').val(),
			cache: false,
			success: function(response){
				if (response == 1)
				{
					alert(_s.js.thanks_featured);
				}
			}
		});
		return false;
	});
	
	// detect if 'still' was requested
	if (viewDragging){showPlayControls();}

	// Update comment box title & button if needed
	if ($('#comment_content').val())
	{
		checkCommentBox();
		$('#comment_content').focus();
	}
	
	if ($('.commentError').length)
	{
		window.location.hash = "addcomment"; 
		$('#comment_content').focus();
	}

	// Update comment box title & button if needed
	$('#comment_content').keydown(function(event){
		if (event.keyCode == 13)
		{
			$('#frm_comment').submit();
		}
	});

	$(function(){
		$('.auto-submit-star').rating({
			callback: function(value, link){
				$.ajax({
					url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/rate-photo/' + $('#js_photo_ident').val() + '/' + value,
					cache: false,
					success: function(response){
						rating = parseFloat(response);
						if (rating)
						{
							$('#avg_rating').html(_s.js.photo_rating + ': ' + rating);
						}
					}
				});
			}
		});
		$('.rating-cancel').hide();
	});
});

function buyPhoto(t)
{
	$.ajax({
		url: $('#js_app_url').val() + $('#js_lang_url').val() + 'ajx/' + $(t).parent().attr('id').replace(/_/g,'/'),
		cache: false,
		success: function(response){
			if (response == 1)
			{
				location.href=$('#my_cart').attr('href');
			}
		}
	});
}

$(function() {

	$('#buy_photo0').click(function(){buyPhoto(this);});
	$('#buy_photo1').click(function(){buyPhoto(this);});
	$('#buy_photo2').click(function(){buyPhoto(this);});

	// left slider for animation
	$("#slider").slider({
		value: 0,
		min: 0,
		max: 10,
		step: 1,
		slide: function(event, ui){
			setHorizontal(10 - ui.value);
			$("#slider_duplicate").slider('option','value', ui.value);
		},
		change: function(event,ui){
			stopAnimation();
		}
	});
	$('#slider').mousedown(function(){stopAnimation();});
	
	// right slider for animation
	$("#slider_duplicate").slider({
		value: 0,
		min: 0,
		max: 10,
		step: 1,
		slide: function(event, ui){
			setHorizontal(10 - ui.value);
			$("#slider").slider('option','value', ui.value);
		},
		change: function(event,ui){
			stopAnimation();
		}
	});
	$('#slider_duplicate').mousedown(function(){stopAnimation();});
	
	// left slider for depth
	$("#sliderDepth").slider({
		value: 5,
		min: 0,
		max: 10,
		step: 1,
		slide: function(event, ui){
			setDepth(ui.value);
			$("#sliderDepth_duplicate").slider('option','value',ui.value);
		}
		
	});
	
	// right slider for depth
	$("#sliderDepth_duplicate").slider({
		value: 5,
		min: 0,
		max: 10,
		step: 1,
		slide: function(event, ui){
			setDepth(ui.value);
			$("#sliderDepth").slider('option','value',ui.value);
		}
		
	});
	
	// left play button
	$('#playBtn').click(function(){goAnimate();});
	
	// left pause button
	$('#pauseBtn').click(function(){
		stopAnimation();
		$("#slider").slider("option", "value", viewX);
		$("#slider_duplicate").slider("option", "value", viewX);
	});
	
	// right play button 
	$('#playBtn_duplicate').click(function(){goAnimate();});
	
	// right pause button
	$('#pauseBtn_duplicate').click(function(){stopAnimation();});
	
	$('#vdd').click(function(){
		if (!viewDragging)
		{
			// stop animation
			stopAnimation();
			$("#slider").slider("option", "value", viewX);
			$("#slider_duplicate").slider("option", "value", viewX);
		}
		else
		{
			// animate
			goAnimate();
		}
	});

	$('#edit_btn').click(function(){
		$('#edit_btn').hide();
		$('#edit_btn2').hide();
		$('#photo_title').hide("slide");
		$('#photo_description').hide("slide");
		$('#photo_tags').hide("slide");

		$('#photo_title_input').show("slide");
		$('#photo_description_input').show("slide");
		$('#photo_tags_input').show("slide");
		$('#user_submit_input').show("slide");
	});
	$('#edit_btn2').click(function(){
		$('#edit_btn').hide();
		$('#edit_btn2').hide();
		$('#photo_title').hide("slide");
		$('#photo_description').hide("slide");
		$('#photo_tags').hide("slide");

		$('#photo_title_input').show("slide");
		$('#photo_description_input').show("slide");
		$('#photo_tags_input').show("slide");
		$('#user_submit_input').show("slide");
	});

	
});

function updateComment(comment)
{
	$('#comment_content').val(html_entity_decode(decode(comment)));
	checkCommentBox();
	window.location.hash = "addcomment"; 
}

function checkCommentBox()
{
	comment = $('#comment_content').val();

	if (comment.match(/^\@\d+\ ((\t|\n|.)*)/g))
	{
		arr = comment.split(' ');
		ord = arr[0].substring(1);
		$('#addcomment').html(_s.js.title_reply_to_comment.replace('S3DCMMNTNUM', ord) + '. ' + $('#comment-' + ord + ' .commentBlk p').html());
		$('#comment_button').val(_s.js.button_reply_to_comment);
	}
	else if (comment.match(/^\!\d+\ ((\t|\n|.)*)/g))
	{
		arr = comment.split(' ');
		ord = arr[0].substring(1);
		$('#addcomment').html(_s.js.title_edit_comment.replace('S3DCMMNTNUM', ord));
		$('#comment_button').val(_s.js.button_edit_comment);
	}
	else if (comment.match(/^\-\d+/g))
	{
		arr = comment.split(' ');
		ord = arr[0].substring(1);
		$('#addcomment').html(_s.js.title_delete_comment.replace('S3DCMMNTNUM', ord));
		$('#comment_button').val(_s.js.button_delete_comment);
	}
	else
	{
		$('#addcomment').html(_s.js.title_add_comment);
		$('#comment_button').val(_s.js.button_add_comment);
	}
}

function encode(unencoded) {
	return encodeURIComponent(unencoded);
}

function decode(encoded) {
	return decodeURIComponent(encoded.replace(/\+/g,  " "));
}

function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str;
  return ta.value;
}
