/* FOTOKUNST FUNCTIONS */

var curCategory = 1;
var curCategoryUrl = '';
var curPhotographer = '';
var curPhotographerUrl = '';
var pathToImgDir = 'typo3conf/ext/iwshop/static/img/';
var frameWidth = new Array();
frameWidth['smal.mat.sort'] = 1.1;
frameWidth['bred.mat.sort'] = 2.5;
frameWidth['solv'] = 2.1;
frameWidth['rund.hvid'] = 1.1;

var categoryData = {
	2 : {
		mode : 'free',
		tab : 1
	},
	1 : {
		mode : 'free',
		tab : 2
	},
	3 : {
		mode : 'fixed',
		tab : 1
	},
	99 : {
		mode: 'nyheder',
		tab : 1
	}
};

function selectCategory(num, el) {
	curCategory = num;

	var $el = $(el);
	var $box = $el.parents('div.sideBar-box');
	var $boxClass = $box.attr('class').match(/category-(\w+)/)[1];
	var $boxes = $el.parents('div#lcol').find('> div.sideBar-box');
	$boxes.each(function(ix, elem) {
		var $elem = $(elem);
		var $table = $elem.find('> h2 + table');
		$table.removeClass('tab-0').removeClass('tab-1').removeClass('tab-2').removeClass('tab-3');
		var $elemClass = $elem.attr('class').match(/category-(\w+)/)[1];
		if ($boxClass == $elemClass) {
			$table.addClass('tab-' + categoryData[num].tab);
		} else {
			$table.addClass('tab-0');
		}
		$elem.find('.menu .left a, .menu .right a').remove();
	});

	selectPhotographer(curPhotographer, curCategory, false);
}

function selectPhotographer(ID, categoryID, obj) {
  curPhotographer = ID;
	curCategory = categoryID;
	if (obj) {
		$('#lcol .menu a').removeClass('boldish');
		$(obj).addClass('boldish');
	}

	if (typeof($(obj).attr('href')) !== 'undefined')
    url = urlsArray[curCategory] + '/' + $(obj).attr('href').substring(1);
  else
    url = urlsArray[curCategory];
  
  window.location.hash = url;  
  
  // if(console) console.log('Selecting fotograf ID='+ID+'...');
	req = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getFotokunstAuthor:' + ID + ':' + curCategory, 'GET', '', loadPhotographer);
	req.send();
}

function loadPhotographer(XML) {
	// if(console) console.log('Got AJAX response!');
	var nodes = $(XML).find('photos > numeric');
	var holder = g('ccol');
  
	/*
	 * try{ holder.innerHTML = ''; } catch(e) { for(var i = 0; i <
	 * holder.childNodes.length; i++) holder.removeChild(holder.childNodes[i]); }
	 */
	$(holder).empty();

	uncheckDelayedImage();

	var counter = 0;
	var attrs = [
			'id', 'rel', 'href', 'src', 'title'
	];

	// console.log(nodes);

	for ( var i = 0; i < nodes.length; i++) {
		if (nodes[i].nodeType == 3)
			continue;

		var node = nodes[i];

		var pic = {
			title : getXMLvalue(node, 'title'),
			id : getXMLvalue(node, 'uid'),
			artist : getXMLvalue(node, 'authorName'),
			w : getXMLvalue(node, 'stdWidth'),
			h : getXMLvalue(node, 'stdHeight'),
			price : getXMLvalue(node, 'price'),
			img_thumb_small : getXMLvalue(node, 'img_thumb_small'),
			img_preview_small : getXMLvalue(node, 'preview_thumb_small'),
			img_thumb_large : getXMLvalue(node, 'img_thumb_large'),
			img_preview_large : getXMLvalue(node, 'preview_thumb_large'),
			img_3 : getXMLvalue(node, 'preview_3'),
			img_4 : getXMLvalue(node, 'preview_4'),
			img_5 : getXMLvalue(node, 'preview_5'),
			box_type : getXMLvalue(node, 'box_type'),
			saptext_1 : getXMLvalue(node, 'saptext_1'),
			saptext_2 : getXMLvalue(node, 'saptext_2')
		};

		// console.log('node['+i+'] : found pic data');
		// console.log(pic);

		counter++;
		var $dd = $('#fotoBoxTemplate').clone().attr('id', 'fotoBox-' + pic.id).appendTo(holder);

		// console.log('node['+i+'] : found $dd');

		var dd = $dd.find('div.description');
		if (pic.title.length > 20) {
			dd.find('h3.title').text(pic.title.substr(0, 18) + '...').attr('title', pic.title);
		} else {
			dd.find('h3.title').text(pic.title);
		}
		dd.find('span.artist').html('&nbsp;' + pic.artist);

		var possible_prices = [];
		if (pic.box_type == 4 || pic.box_type == 5) {
			dd.find('.fotokunst-free-size-template').remove();
			var thb = dd.find('a.thickbox');
			thb.attr('href', str_replace('$UID$', pic.id, thb.attr('href')));
			var thc = dd.find('div.saptext-2-value');
			thc.attr('id', str_replace('$UID$', pic.id, thc.attr('id')));
			var sap2 = thc.find('div');
			sap2.brtext(pic.saptext_2);
			var sap1 = dd.find('span.saptext-1');
			sap1.brtext(pic.saptext_1);

			var selSize = dd.find('.fotokunst-fixed-sizes-template');
			if (pic.box_type == 4) {
				$dd.addClass('fixed-size');
				selSize.remove();
				possible_prices.push(pic.price);
			} else {
				$dd.addClass('fixed-multi-size');
				var sel = selSize.find('select');
				var sizes = $(nodes[i]).find('fixed_sizes numeric');
				$.each(sizes, function(ix, el) {
					var $o = $('<option />').val(ix);
					var $el = $(el);
					$o.text($el.xmval('h') + 'x' + $el.xmval('w') + ' ' + $el.xmval('measure') + ' ('+beforePriceCurrency+' ' + dk_money($el.xmval('price')) + ',- )');
					sel.append($o);
					possible_prices.push($el.xmval('price'));
				});
			}
		} else {
			possible_prices.push(pic.price);
			$dd.addClass('user-size');
			dd.find('.fotokunst-fixed-size-template').remove();
			dd = $dd.find('.description td:first');
			dd.html(str_replace('$WIDTH$', pic.w, str_replace('$HEIGHT$', pic.h, dd.html())));
		}

		$dd.find('strong.price').text(pic.price + afterPriceCurrency).data('possiblePrices', possible_prices);
		$dd.find('div.addToCart a').attr('id', 'cartLinkUID-' + pic.id);

		dd = $dd.find('div.iconHolder');
		var tmp = dd.find('a').attr('title', pic.title);
		tmp = tmp.attr('href', str_replace('$PREVIEW_IMG_LARGE$', pic.img_preview_large, str_replace('$UID$', pic.id, tmp.attr('href')))).find('img');
		var imgPath = str_replace('$PREVIEW_IMG$', '', tmp.attr('src'));
		tmp.attr('src', str_replace('$PREVIEW_IMG$', pic.img_preview_small, tmp.attr('src')));

		dd = $dd.find('table.imagePreview div');

		var previewImage = dd.find('img');
		var goodSrc = str_replace('$IMG$', pic.img_thumb_small, dd.find('img').attr('src'));
		if (counter < 2) {
			previewImage.attr('src', goodSrc);
		} else if (counter < 3) {
			previewImage.attr('src', goodSrc).attr('delayed_source', goodSrc);
		} else {
			previewImage.attr('src', '').attr('delayed_source', goodSrc);
		}

		tmp = dd.find('a.plus').attr('id', 'imgplus-' + pic.id).attr('title', pic.title);
		tmp.attr('href', str_replace('$IMG_LARGE$', pic.img_thumb_large, str_replace('$UID$', pic.id, tmp.attr('href'))));

		dd = $dd.find('div.gallery');
		dd = dd.attr('id', 'imgGallery' + pic.id).find('div.thumbsHolder a:first');
		tmp = dd.click(function() {
			swapImageSimple($(this).children().attr('src'));
			return false;
		}).find('img');
		tmp.attr('src', str_replace('$IMG_LARGE$', pic.img_thumb_large, tmp.attr('src')));

		dd = dd.next();
		if (pic.img_preview_large != '') {
			tmp = dd.click(function() {
				swapImageSimple($(this).children().attr('src'));
				return false;
			}).find('img');
			tmp.attr('src', str_replace('$PREVIEW_IMG_LARGE$', pic.img_preview_large, tmp.attr('src')));
		} else {
			dd.empty();
		}

		dd = dd.next();
		if (pic.img_3 != '') {
			tmp = dd.click(function() {
				swapImageSimple($(this).children().attr('src'));
				return false;
			}).find('img');
			tmp.attr('src', str_replace('$PREVIEW_3$', pic.img_3, tmp.attr('src')));
		} else {
			dd.empty();
		}

		dd = dd.next();
		if (pic.img_4 != '') {
			tmp = dd.click(function() {
				swapImageSimple($(this).children().attr('src'));
				return false;
			}).find('img');
			tmp.attr('src', str_replace('$PREVIEW_4$', pic.img_4, tmp.attr('src')));
		} else {
			dd.empty();
		}

		dd = dd.next();
		if (pic.img_5 != '') {
			tmp = dd.click(function() {
				swapImageSimple($(this).children().attr('src'));
				return false;
			}).find('img');
			tmp.attr('src', str_replace('$PREVIEW_5$', pic.img_5, tmp.attr('src')));
		} else {
			dd.empty();
		}

		if (pic.img_preview_small == '')
			$('#fotoBox-' + pic.id + ' .iconHolder a').remove();

		$dd.show();

		// console.log('done with node['+i+']');
	}
	if (counter == 0) {
		holder.innerHTML = '&nbsp;';
	}

	delayLoadImages();
	bindQuantityUpdate();

	// Load author list.. again
	var authors = $(XML).find('authors > numeric');

	var catContainer = $('#lcol .category-' + categoryData[curCategory].mode + ' tr.ra .menu');

	var $menuLeft = catContainer.find('.left').html('');
	for ( var i = 0; i < Math.round(authors.length / 2); i++) {
		$menuLeft.append(produceAuthorLink(authors[i]));
	}

	var $menuRight = catContainer.find('.right').html('');
	for ( var i = Math.round(authors.length / 2); i < authors.length; i++) {
		$menuRight.append(produceAuthorLink(authors[i]));
	}

	if (catContainer.find('a.boldish').length == 0) {
    if (curPhotographerUrl != ''){
		  $('a[href=#'+curPhotographerUrl+']').click();
      curPhotographerUrl = '';  
    }
    else
      catContainer.find('a:first').click();
	}

	tb_init('a.thickbox, area.thickbox, input.thickbox');
}

function produceAuthorLink(authorXML) {
	var author = {
		id : getXMLvalue(authorXML, 'uid'),
		name : getXMLvalue(authorXML, 'name'),
		url : getXMLvalue(authorXML, 'url')
	};
	
	$a = $("<a></a>").attr('href', '#' + author.url).text(author.name).click(function() {
		selectPhotographer(author.id, curCategory, $(this));
		return false;
	});
	if (author.id == curPhotographer) {
		$a.addClass('boldish');
	}
	return $a;
}

function selectImage(linkObj) {
	var ID = linkObj.id.substr(12);
	// if(console) console.log('Selecting image ID='+ID+'...');
	var f = g('nav_form');
	f.imgID.value = ID;
	f.submit();
}

/*
 * function calcPrice(w, h, ftype, coef) { if(!coef) coef = 1;
 * 
 * return calcImagePrice(w, h, coef)+calcFramePrice(w, h, ftype, coef); }
 * 
 * 
 * function calcImagePrice(w, h, coef) { return Math.round(coef * 1.25 * (190 +
 * 800*w*h/10000)); }
 * 
 * function calcFramePrice(w, h, ftype, coef) { var base = 75; if(ftype ==
 * 'option2') base = 78; if(ftype == 'option3') base = 175; return
 * Math.round(coef * 1.25 * 2*(w+h)/100*base); }
 */

function clickButton(which, frames) {
	var f = g('nav_form');
	f.button.value = which;
	if (frames)
		f.frameType.value = frames;
	if (f.onsubmit) {
		var res = f.onsubmit();
		if (typeof (res) == 'undefined' || res)
			f.submit();
		else
			return false;
	} else
		f.submit();
}

function increaseSize() {
	changeSize(5);
}

function decreaseSize() {
	changeSize(-5);
}

function changeSize(delta) {
	var f = g('nav_form');
	var w = f.width.value * 1.0;
	var h = f.height.value * 1.0;

	var s = {
		w : $('#thumb_image').width(),
		h : $('#thumb_image').height()
	};

	var newW;
	var newH;

	if (w > h) {
		newW = w + delta;
		// newH = Math.round((w+delta)*h/w);
		newH = Math.round(newW * s.h / s.w);
	} else {
		newH = h + delta;
		// newW = Math.round((h+delta)*w/h);
		newW = Math.round(newH * s.w / s.h);
	}

	/*
	 * if(min(newW, newH) < 20) { if(newW < newH) { newW = 20; newH =
	 * Math.round(newW*h/w); if(newH%5 > 0) { newH = newH - newH%5 + 5; newW =
	 * Math.round(newH*w/h); } } else { newH = 20; newW = Math.round(newH*w/h);
	 * if(newW%5 > 0) { newW = newW - newW%5 + 5; newH = Math.round(newW*h/w); } } }
	 */
	var validSize = validateSize(newW, newH);

	if (delta < 0 && validSize.w > f.width.value)
		validSize = {
			w : f.width.value,
			h : f.height.value
		};
	if (delta > 0 && validSize.w < f.width.value)
		validSize = {
			w : f.width.value,
			h : f.height.value
		};

	f.width.value = validSize.w;
	f.height.value = validSize.h;

	g('newWidth').innerHTML = validSize.w;
	g('newHeight').innerHTML = validSize.h;

	// try{ console.log(validSize.w+"/"+validSize.h+" =>
	// "+validSize.w/validSize.h); }
	// catch(e) {}

	updatePrices();
}

function initStep3(w, h) {
	var imgData = getObjectData(g('thumb_image'));
	if (!w || !h) {
		if (imgData.w > imgData.h) {
			w = 90;
			h = Math.round(90.0 * imgData.h / imgData.w);
		} else {
			h = 90;
			w = Math.round(90.0 * imgData.w / imgData.h);
		}
	}
	var f = g('nav_form');
	f.width.value = w;
	f.height.value = h;
	g('newWidth').innerHTML = w;
	g('newHeight').innerHTML = h;

	t = getObjectData(g('thumb_image'));
	hmp = getObjectData(g('hMeasure').parentNode);
	g('hMeasure').style.position = 'relative';
	g('hMeasure').style.left = t.x - hmp.x + 'px';
	g('hMeasure').style.width = t.w + 'px';

	// g('vMeasure').style.position = 'relative';
	// g('vMeasure').style.top = (325-t.h)/2+'px';
	g('vMeasure').style.height = t.h + 'px';

	updatePrices(w, h);
}

function updatePrices(w, h, f, pc) {
	if (!w)
		w = g('nav_form').width.value * 1;
	if (!h)
		h = g('nav_form').height.value * 1;
	if (!f)
		f = frame_type.charAt(frame_type.length - 1) * 1;
	/*
	 * if(!pc) pc = price_coef; price_coef = pc;
	 */

	$('#td_image_prod').html(str_replace('%SIZE%', w + 'x' + h + 'cm', product_name));
	$('#td_frame_prod').html(str_replace('%SIZE%', w + 'x' + h + 'cm', frame_name));

	var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getPrice:fotokunst', 'POST', 'w=' + w + '&h=' + h + '&f=' + f + '&id=' + item_id,
			updatePricesLoader);
	r.send();
}

function updatePricesLoader(XML) {

	var imgPrice = getXMLvalue(XML, 'PicturePrice') * 1; // - getXMLvalue(XML,
	// 'FramePrice') * 1;
	var frmPrice = getXMLvalue(XML, 'FloatFramePrice') * 1;
	var totPrice = getXMLvalue(XML, 'TotalPrice') * 1;

	$('#td_image_price').html(imgPrice + afterPriceCurrency);
	$('#td_frame_price').html(frmPrice + afterPriceCurrency);
	$('#td_total_price').html(totPrice + afterPriceCurrency);

	$('#td_image_price').css('color', 'red');
	$('#td_frame_price').css('color', 'red');
	$('#td_total_price').css('color', 'red');
	setTimeout('unblinkPrices()', 500);
}

function unblinkPrices() {
	$('#td_image_price').css('color', '');
	$('#td_frame_price').css('color', '');
	$('#td_total_price').css('color', '');
}

function unsetOtherChoices(o) {
	f = o.form;
	if (!o.checked)
		o = document.createElement('input');
	for ( var i = 0; i < f.elements.length; i++) {
		e = f.elements[i];
		if (e.type == 'checkbox' && e.name == o.name && e.value != o.value && e.checked)
			e.checked = false;
	}
	fixGlows(o);
	framePreview(o.value);
	updateProduct();
}

function framePreview(style) {
	var icm = {
		w : g('newWidth').innerHTML * 1,
		h : g('newHeight').innerHTML * 1
	};
	var img = getObjectData(g('thumb_image'));

	var frameW = Math.round(img.w / icm.w * frameWidth[style]);
	if (frameW < 1)
		frameW = 1;

	var pos = [
			'TL', 'T', 'TR', 'L', 'R', 'BL', 'B', 'BR'
	];
	if (style == '') {
		for ( var i = 0; i < pos.length; i++) {
			g('frame' + pos[i]).style.display = 'none';
		}
	} else {
		for ( var i = 0; i < pos.length; i++) {
			o = g('frame' + pos[i]);
			o.src = pathToImgDir + 'frames/' + style + '.' + pos[i].toLowerCase() + '.jpg';
			if (pos[i] == 'T' || pos[i] == 'B') {
				o.width = img.w;
				o.height = frameW;
			}
			if (pos[i] == 'L' || pos[i] == 'R') {
				o.height = img.h;
				o.width = frameW;
			}
			if (pos[i].length == 2) {
				o.width = frameW;
				o.height = frameW;
			}
			o.style.display = 'block';
		}
	}
}

function fixGlows(o) {

	var elems = [
			g('table.smal.mat.sort'), g('table.bred.mat.sort'), g('table.solv'), g('table.rund.hvid')
	];

	for ( var i = 0; i < elems.length; i++) {
		var e = elems[i];
		if (e.id == 'table.' + o.value)
			$(e).removeClass('shadow').addClass('glow').addClass('inuse');
		else
			$(e).addClass('shadow').removeClass('glow').removeClass('inuse');
	}

}

function restoreFrameChoice(choice) {
	if (choice == 'smal.mat.sort')
		g('fstyle_check1').click();
	if (choice == 'bred.mat.sort')
		g('fstyle_check2').click();
	if (choice == 'solv')
		g('fstyle_check3').click();
	if (choice == 'rund.hvid')
		g('fstyle_check4').click();
}

function updateProduct() {
	var ftype = '';
	var icm = {
		w : g('newWidth').innerHTML * 1,
		h : g('newHeight').innerHTML * 1
	};
	var elems = [
			g('fstyle_check1'), g('fstyle_check2'), g('fstyle_check3'), g('fstyle_check4')
	];
	for ( var i = 0; i < elems.length; i++) {
		var e = elems[i];
		if (e.checked) {
			switch (e.value) {
				case 'smal.mat.sort':
					ftype = 'Smal mat sort';
					break;
				case 'bred.mat.sort':
					ftype = 'Bred mat sort';
					break;
				case 'solv':
					ftype = 'Sølv';
					break;
				case 'rund.hvid':
					ftype = 'Rund hvid';
					break;
				default:
					ftype = e.value;
			}
		}
	}

	if (ftype != '')
		ftype = ': ' + ftype;

	$('#td_frame_prod').html(str_replace('%TYPE%', ftype, frame_prod));
}

function validateSize(w, h) {
	var newW = w;
	var newH = h;

	var enlarge = true;
	var temp = 0;

	if (newW < newH) {
		if (newH > 300) {
			newW = Math.round(300 / newH * newW);
			newH = 300;
			enlarge = false;
		}
		if (newW > 150) {
			newH = Math.round(150 / newW * newH);
			newW = 150;
			enlarge = false;
		}
		if (newW < 20) {
			newH = Math.round(20 / newW * newH);
			newW = 20;
			enlarge = true;
		}

		if (newH % 5 > 0) {
			temp = newH - newH % 5 + (enlarge ? 5 : 0);
			newW = Math.round(temp / newH * newW);
			newH = temp;
		}
	} else {
		if (newW > 300) {
			newH = Math.round(300 / newW * newH);
			newW = 300;
			enlarge = false;
		}
		if (newH > 150) {
			newW = Math.round(150 / newH * newW);
			newH = 150;
			enlarge = false;
		}
		if (newH < 20) {
			newW = Math.round(20 / newH * newW);
			newH = 20;
			enlarge = true;
		}

		if (newW % 5 > 0) {
			temp = newW - newW % 5 + (enlarge ? 5 : 0);
			newH = Math.round(temp / newW * newH);
			newW = temp;
		}
	}

	return {
		w : newW,
		h : newH
	};
}

function checkFrameChoice() {
	var ok = $('input[name=fstyle]').length == 0 || g('fstyle_check1').checked || g('fstyle_check2').checked || g('fstyle_check3').checked
			|| g('fstyle_check4').checked;
	if (!ok)
		alert(noFrameChosenError);
	else
		g('frame_style').value = (g('fstyle_check1') && g('fstyle_check1').checked ? g('fstyle_check1').value : (g('fstyle_check2')
				&& g('fstyle_check2').checked ? g('fstyle_check2').value : (g('fstyle_check3') && g('fstyle_check3').checked
				? g('fstyle_check3').value
				: (g('fstyle_check4') && g('fstyle_check4').checked ? g('fstyle_check4').value : ''))));
	return ok;
}

