/* Collage FUNCTIONS */

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;

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 f.submit();
}


function unsetOtherChoices(o) {
	if(!o.checked) o = document.createElement('input');
	var checkstatus = o.checked;
	$('input[name=fstyle]').each( function() { $(this)[0].checked = false; } );
	o.checked = checkstatus;
	fixGlows(o);
	framePreview(o.value);
}


function framePreview(style) {
	var icm = {w:g('newWidth').innerHTML*1, h:g('newHeight').innerHTML*1};
	// var img = getObjectData(g('sampleImage'));
	var img = updatePreviewBox();
	// console.log(img);
	
	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';
			g('frame'+pos[i]).width = '';
			g('frame'+pos[i]).height = '';
		}
// }
// else {
	

	if(style != '') {
		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') $('#fstyle_check1').click();
	if(choice == 'bred.mat.sort') $('#fstyle_check2').click();
	if(choice == 'solv') $('#fstyle_check3').click();
	if(choice == 'rund.hvid') $('#fstyle_check4').click();
}

function calcPrice(w, h, ft, ic) {	// width, height, frame-type, image-count
	var image = 190+Math.round(800*w*h/10000);
	var frame = 75;
	switch (ft) {
		case 2: frame = 78; break;
		case 3: frame = 175; break;
	}
	frame = Math.round(2*(w+h)/100*frame);
	var design = (typeof(ic) != 'undefined' ? 1200+300*ic : '?');
	return {image:image, frames:frame, design:design};
}

function updatePriceBox() {
	var w = g('nav_form').width.value*1;
	var h = g('nav_form').height.value*1;
	var f = g('nav_form').frame_type.value.charAt( g('nav_form').frame_type.value.length - 1 );
	
	var size = w+'x'+h+' cm';
	// var prices = calcPrice(w, h, g('nav_form').frame_type.value.substr(6)*1);
	
	$('#product_image').html( str_replace('%SIZE%', size, img_price_str) );
	// g('price_image').innerHTML = prices.image+' DKK';
	
	$('#product_frame').html( str_replace('%SIZE%', size, frame_price_str) );
	// g('price_frame').innerHTML = prices.frames+' DKK';
	
	var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getPrice:collage', 'POST', 'w='+w+'&h='+h+'&f='+f+'&n=0', updatePriceBoxLoader)
	r.send();
}

function updatePriceBoxLoader(XML) {
	$('#price_image').html( getXMLvalue(XML, 'PicturePrice')+afterPriceCurrency );
	$('#price_frame').html( getXMLvalue(XML, 'FloatFramePrice')+afterPriceCurrency );
}

function increaseSize(t) {	// type
	var w = g('nav_form').width.value*1;
	var h = g('nav_form').height.value*1;

	if(t == 'h') { g('nav_form').height.value = min( h+5, (w > 150 ? 150 : 300) ); }
	if(t == 'w') { g('nav_form').width.value = min( w+5, (h > 150 ? 150 : 300) ); }
	
	updatePriceBox();
	updatePreviewBox();
	updateFramePreview();
}

function decreaseSize(t) {	// type
	var w = g('nav_form').width.value*1;
	var h = g('nav_form').height.value*1;

	if(t == 'h') { g('nav_form').height.value = max( h-5, 20 ); }
	if(t == 'w') { g('nav_form').width.value = max( w-5, 20 ); }
	
	updatePriceBox();
	updatePreviewBox();
	updateFramePreview();
}

function updatePreviewBox() {
	var w = g('nav_form').width.value;
	var h = g('nav_form').height.value;
	
	var stdW = 450;
	var stdH = 325;
	
	var newW = stdW;
	var newH = stdH;
	
	if(w/stdW > h/stdH) {
		newH = Math.round(h*stdW/w);
	}
	else {
		newW = Math.round(w*stdH/h);
	}
	
	g('sampleImage').style.width = newW+'px';
	g('sampleImage').style.height = newH+'px';
	
	g('hMeasure').style.width = newW+'px';
	g('vMeasure').style.height = newH+'px';
	
	g('newWidth').innerHTML = w;
	g('newHeight').innerHTML = h;
	
	return {w:newW, h:newH};
}

function updateFramePreview() {
	if( g('fstyle_check1') != null) {
		var o = null;
		if(g('fstyle_check1').checked) o = g('fstyle_check1');
		if(g('fstyle_check2').checked) o = g('fstyle_check2');
		if(g('fstyle_check3').checked) o = g('fstyle_check3');
		if(g('fstyle_check4').checked) o = g('fstyle_check4');
	
		if(o != null) framePreview(o.value);
		else updatePreviewBox();
	}
	else {
		updatePreviewBox();
	}	
}

function addNewImageBox() {
	var counter = $('.collageImagesContainer .collageImageUploadBox').length+1;
	var target = $('.collageImagesContainer .clearer');
	var tpl = $('.collageImageUploadBoxTemplate');
	var copy = tpl.clone().removeClass('collageImageUploadBoxTemplate').addClass('collageImageUploadBox').insertBefore(target).show();
	copy.find('h3').text( copy.find('h3').text()+' '+counter );
	copy.find(':hidden').attr( 'name', 'usrImgID-'+counter );
	copy.find(':checkbox').attr( 'name', 'paper-'+counter );
	copy.find('iframe').attr( 'src', copy.find('iframe').attr( 'src' )+counter ).attr('name', 'uFrame' + counter).load(ImageUploader.FrameLoaded);
	copy.find('a.gradButton').attr('href', window.location+'#').click( function() { startUpload($(this).parent()); } ).parent().hide();
	copy.attr('id', 'CIUB-'+counter).addClass('upload-container');
	copy.find('.emptyBar').hide();
}

function removeLastImageBox() {
	var target = $('.collageImagesContainer .clearer').prev().remove();
}

function updateBoxNumber() {
	var n = g('nav_form').how_many.value*1;
	var c = $('.collageImagesContainer .collageImageUploadBox').length;
	var d = n-c;
	
	while(d > 0) {
		addNewImageBox();
		d--;
	}
	while(d < 0) {
		removeLastImageBox();
		d++;
	}
}

function updatePriceBox2() {
  var w = imgWidth;
  var h = imgHeight;
  var f = frameType;
	var n = g('nav_form').how_many.value*1;
	var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getPrice:collage', 'POST', 'w='+w+'&h='+h+'&f='+f+'&n='+n, updatePriceBox2Loader)
	r.send();
}

function updatePriceBox2Loader(XML) {
	var n = g('nav_form').how_many.value*1;
  
	$('#td_img_price').html( getXMLvalue(XML, 'PicturePrice')-getXMLvalue(XML, 'FramePrice')+afterPriceCurrency );
	$('#td_frame_price').html( getXMLvalue(XML, 'FloatFramePrice')+afterPriceCurrency );
	
	if(n > 0) {
		$('#td_design_price').html( getXMLvalue(XML, 'DesignPrice')+afterPriceCurrency );
		$('#td_total_price').html( getXMLvalue(XML, 'TotalPrice')+afterPriceCurrency );
	}
	else {
		$('#td_design_price').html( '?' );
		$('#td_total_price').html( '?' );
	}
}

function clickCheck(o) {
	var box = $(o).parents('.upload-container');
	if(o.checked) {
		box.find('img').attr('src', 'fileadmin/templates/_img/collage/papir_foto.jpg').css('width', '').css('height', '').css('border', 'none');
		var frm = box.find('iframe');
		frm.attr('src', '');
		var upl = ImageUploader.Instances[frm.attr('name')];
		if(upl) {
			upl.abortUpload();
		}
		box.find('.iframeBar').hide();
		box.find('.ProgBar').hide();
		box.find('.emptyBar').toggle(box.find(':hidden').val() == '');
		box.find('a.gradButton').text( deletePictureText ).unbind('click').click( function() {
			resetImageBox($(this).parents('.upload-container'));
			return false;
		});
	}
	else {
		resetImageBox(box);
	}
}

function resetImageBox(box) {
	var $box = $(box);
	var counter = $box.attr('id');
	counter = counter.substr( counter.length -1 );
	$box.find(':checkbox')[0].checked = false;
	$box.find(':hidden').val('');
	$box.find('img').attr('src', '').css('width', '').css('height', '').attr('src', 'fileadmin/templates/_img/collage/no_image.jpg').css('margin-top', 0).css('border', 'none');
	$box.find('a.gradButton').text( uploadPictureText ).unbind('click').click( function () { startUpload($(this).parent()); return false } ).parent().hide();
	$box.find('iframe').attr('src', 'typo3conf/ext/iwshop/uploader/iframe.php?dir=fileadmin/uploads/&mini=1&btn_name='+btn_name+'&id='+counter);
	$box.find('.iframeBar').show().prev().css('margin-bottom', '5px');
	$box.find('.ProgBar').hide();
	$box.find('.emptyBar').hide();
}

function startUpload(node) {
	var box = node.parents('.upload-container');
	var frame = box.find('iframe');
	frame[0].contentWindow.initUpload();
	return false;
}

function startUploadBar(uploader) {
	// console.log('Got id = '+id);
	var box = uploader.box();
	box.find('.iframeBar').hide().prev().css('margin-bottom', '5px');
	box.find('.ProgBar').show();
	box.find('.emptyBar').hide();
	box.find('a.gradButton').text( deletePictureText ).unbind('click').click( function () { 
		resetImageBox( $(this).parent().parent());
		return false;
	} );
	uploader.cancelPing = false;
	uploader.queuePing();
}

function voidUpload(uploader) {
	var box = uploader.box();
	box.find('.iframeBar').show();
	box.find('.ProgBar').hide();
	box.find('a.gradButton').text( uploadPictureText ).unbind('click').click( function () { 
		startUpload($(this).parent()); 
		return false;
	} );
	uploader.stopProgressBar();
}

function upload_error(uploader, msg) {
	alert(window.uploadErrorMessage || 'Upload failed!');
	resetImageBox(uploader.box());
}

function upload_complete(uploader, imgID, imgFile, w, h) {
	uploader.stopProgressBar();

	displayUploadedImage(imgID, imgFile, uploader.index, w, h);
}

function displayUploadedImage(imgID, imgFile, n, w, h) {
	var box = $('#CIUB-'+n);
	box.find('iframe').attr('src', '');
	box.find('.iframeBar').hide();
	box.find('.ProgBar .progressIn').css('width', '0px');
	box.find('.ProgBar .progressLabel').text('0% (Inactive)');
	box.find('.ProgBar').hide();
	box.find('.emptyBar').hide();
	box.find('.gradButton').parent().show();
	box.find('img').attr('src', imgFile).css('border', 'solid 1px #808080');
	if(w/h > 128/70) {
		box.find('img').css({
			width: '128px'
			, 'margin-top': Math.round((72-(128*h/w))/2)+'px'
		}).parent().css('height', '75px');
	} else {
		box.find('img').css({
			height: '70px'
			, 'margin-top': 0
		});
	}
	box.find(':hidden').val(imgID);
}

function clickButtonSpecial(which) {
	var n = g('nav_form').how_many.value*1;
	if(n == 0) {
		alert(notAllUploadedText);
		return false;
	}
	
	var allFound = true;
	for(var i = 1; i <= n; i++) {
		var selector = $('#CIUB-' + i);
		var found = (selector.find(':hidden').val() * 1 > 0) || (selector.find(':checkbox:checked').length > 0);

		allFound = allFound && found;
	}
	if(!allFound) {
		alert(notAllUploadedText);
		return false;
	}
	else clickButton(which);
}

function restoreImages(idStr) {
	var ids = idStr.split(',');
	$('#lcol').find('select').val(ids.length);
	updateBoxNumber();
	for(var i = 0; i < ids.length; i++) {
		if(ids[i] == '') continue;
		if(ids[i] == 'P') {
			$('#CIUB-'+(i+1)).find(':checkbox').click();
		}
		else {
			$('#CIUB-'+(i+1)).find(':hidden').val(ids[i]);
			var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getCollageImage:'+ids[i]+':'+(i+1), 'GET', '', loadSingleImage);
			r.send();
		}
	}
	
}

function makeDeleteButton(obj) {
	return function (box) {
		return function () {
			resetImageBox( box );
			return false;
		}
	}(obj);
}

function loadSingleImage(XML) {
	var imgPath = getXMLvalue(XML, 'img');
	var boxNum = getXMLvalue(XML, 'box');
	var picID = getXMLvalue(XML, 'ID');
	var w = getXMLvalue(XML, 'w');
	var h = getXMLvalue(XML, 'h');
	
	var box = $('#CIUB-'+boxNum);
	box.find('img').attr('src', imgPath).css('border', 'solid 1 #808080');
	box.find(':hidden').val( picID );
	box.find('iframe').attr('src', '');
	box.find('.iframeBar').hide();
	box.find('a.gradButton').text( deletePictureText ).unbind('click').click( makeDeleteButton(box) );
	box.find('.deleteBar').show();

	if(w/h > 128/70) {
		box.find('img').css({
				width: '128px'
				, 'margin-top': Math.round((72-(128*h/w))/2)+'px'
		}).parent().css('height', '75px');
	} else {
		box.find('img').css({
			height: '72px'
			, 'margin-top': 0
		});
	}
}

function filledAllFields() {
	if( $('textarea[name=comment-wishes]').val().length < 1 ||  $('textarea[name=comment-wishes]').val() == box1_text) return false;
	if( $('textarea[name=comment-text]').val().length < 1 ||  $('textarea[name=comment-text]').val() == box1_text) return false;
	if( $('textarea[name=comment-colors]').val().length < 1 ||  $('textarea[name=comment-colors]').val() == box1_text) return false;
	return true;
}

function checkTextAreas(){
    if ($("textarea#comment-wishes").val()==box1_text)
        $("textarea#comment-wishes").css('color','#606060');
    if ($("textarea#comment-text").val()==box2_text)
        $("textarea#comment-text").css('color','#606060');
    if ($("textarea#comment-colors").val()==box3_text)
        $("textarea#comment-colors").css('color','#606060');
    
    if ($("textarea#comment-wishes").val()=='')
        $("textarea#comment-wishes").val(box1_text).css('color','#606060');

    if ($("textarea#comment-text").val()=='')
        $("textarea#comment-text").val(box2_text).css('color','#606060');

    if ($("textarea#comment-colors").val()=='')
        $("textarea#comment-colors").val(box3_text).css('color','#606060');
    
    $("textarea#comment-wishes").focus(function() {  
        if ($(this).val()== box1_text)
            $(this).val("").css('color','#1D1D1D');  
    });

    $("textarea#comment-text").focus(function() {  
        if ($(this).val()== box2_text)
            $(this).val("").css('color','#1D1D1D');  
    });
    
    $("textarea#comment-colors").focus(function() {  
        if ($(this).val()== box3_text)
            $(this).val("").css('color','#1D1D1D');  
    });
}

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;
}

function updatePriceBoxStep4() {
	var w = imgWidth;
	var h = imgHeight;
	var f = frameType;
	var n = $('#input_how_many').val();
	
	var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getPrice:collage', 'POST', 'w='+w+'&h='+h+'&f='+f+'&n='+n, updatePriceBoxStep4Loader);
	r.send();
}

function updatePriceBoxStep4Loader(XML) {
	$('#td_img_price').text( getXMLvalue(XML, 'PicturePrice')+afterPriceCurrency );
	$('#td_frame_price').text( getXMLvalue(XML, 'FloatFramePrice')+afterPriceCurrency );
	$('#td_design_price').text( getXMLvalue(XML, 'DesignPrice')+afterPriceCurrency );
	$('#td_total_price').text( getXMLvalue(XML, 'TotalPrice')+afterPriceCurrency );
}

function disableSendButton() {
	$('.sideBar-navigation .send').css('opacity', 0.25).css('filter', 'alpha(opacity=25)').css('cursor', 'default').unbind('click');
	// console.log('disableSendButton');
}

function enableSendButton() {
	$('.sideBar-navigation .send').css('opacity', 1).css('filter', '').css('cursor', 'pointer').bind('click', function() { clickButton($('.sideBar-navigation .send').text() ) } );
	// console.log('enableSendButton');
}

