/*** PopArt functions ***/

/*
var styleOptions = new Array();
	styleOptions[1] = {price:495, v:1, h:1, p:1};
	styleOptions[2] = {price:545, v:1, h:2, p:1};
	styleOptions[3] = {price:575, v:1, h:3, p:1};
	styleOptions[4] = {price:595, v:2, h:2, p:1};
	styleOptions[5] = {price:645, v:2, h:3, p:1};
	styleOptions[6] = {price:695, v:1, h:1, p:2};
	styleOptions[7] = {price:845, v:1, h:2, p:2};
	styleOptions[8] = {price:1195, v:1, h:3, p:3};
	styleOptions[9] = {price:945, v:2, h:2, p:2};
*/
var styleOptions = new Array();
	styleOptions[1] = {v:1, h:1, p:1};
	styleOptions[2] = {v:1, h:2, p:1};
	styleOptions[3] = {v:1, h:3, p:1};
	styleOptions[4] = {v:2, h:2, p:1};
	styleOptions[5] = {v:2, h:2, p:1};
	styleOptions[6] = {v:1, h:1, p:1};
	styleOptions[7] = {v:1, h:2, p:2};
	styleOptions[8] = {v:1, h:3, p:3};
	styleOptions[9] = {v:2, h:2, p:2};
	
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 btnClick(domChunk) {
	var styleNo = $(domChunk).parent().parent().parent().parent().parent().parent()[0].id.substr(5)*1;	
	$('.activeWrapper').removeClass('activeWrapper').find('a.gradButton').click();
	$('#PSBW-'+styleNo).addClass('activeWrapper').find('a.gradButton').text(unchooseText).unbind('click').click( function() { btnUnclick($(this)); } );
	$('input[name=style]').val(styleNo);
}

function btnUnclick(domChunk) {
	var styleNo = $(domChunk).parent().parent().parent().parent().parent().parent()[0].id.substr(5)*1;	
	$('.activeWrapper').removeClass('activeWrapper');
	$('#PSBW-'+styleNo+' a.gradButton').text(chooseText).unbind('click').click( function() { btnClick($(this)); } );	
	$('input[name=style]').val('');
}

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 = updatePreviewBox();
	
	var frameW = Math.round(img.w/icm.w*frameWidth[style]);
	//var frameH = Math.round(img.h/icm.h*frameWidth[style]);
	//frameW = min(frameW, frameH);
	if(frameW < 1) frameW = 1;
	
	var pos = ['TL', 'T', 'TR', 'L', 'R', 'BL', 'B', 'BR'];
	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 = '';
	}

	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 updatePreviewBox() {
	var w = g('nav_form').width.value;
	var h = g('nav_form').height.value;
	
	var myObj = $('#sampleImage img').css('width', '').css('height', '');
	var stdW = myObj.width(); //450;
	var stdH = myObj.height(); //325;

/*	var newW = $('#sampleImage img').width();
	var newH = $('#sampleImage img').height();
*/
	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';
 */	
 	myObj.css('width', newW+'px').css('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 clickButtonSpecial(which) {
	if($('input[name=style]').val() == '' || $('textarea[name=colors]').val() == '' || $('textarea[name=colors]').val() == box1_text) {
		alert(incompleteText);
		return false;
	}
	else
        clickButton(which);
}

function clickButtonSpecial2(which) {
	var n = styleOptions[$('input[name=popstyle]').val()].p;
	
	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 updatePriceBox() {
	var w = g('nav_form').width.value*1;
	var h = g('nav_form').height.value*1;
	
	var size = w+'x'+h+' cm';
	//var prices = calcPrice(w, h, g('nav_form').popstyle.value, g('nav_form').frame_type.value.substr(6)*1);
	var s = g('nav_form').popstyle.value;
	var f = g('nav_form').frame_type.value.charAt( g('nav_form').frame_type.value.length-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';
	
	//g('price_design').innerHTML = prices.design+' DKK';
	//g('price_total').innerHTML = prices.image+prices.frames+prices.design+' DKK';
	
	var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getPrice:popart', 'POST', 'w='+w+'&h='+h+'&f='+f+'&s='+s, updatePriceBoxLoader)
	r.send();
}

function updatePriceBoxLoader(XML) {
  var f = getXMLvalue(XML, 'FloatFramePrice');
  var p = getXMLvalue(XML, 'PicturePrice');
  var d = getXMLvalue(XML, 'DesignPrice');
  var t = getXMLvalue(XML, 'TotalPrice');

	$('#price_image').html( p+afterPriceCurrency );
	$('#price_frame').html( f+afterPriceCurrency );
	$('#price_design').html( d+afterPriceCurrency );
	$('#price_total').html( t+afterPriceCurrency );
}

function calcPrice(w, h, s, ft) {
	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 = styleOptions[s].price;
	return {image:image, frames:frame, design:design};
}

function clickSquare() {
	if($('#input_square')[0].checked) {
			var styleNo = $('input[name=popstyle]').val();
		var st = styleOptions[styleNo];
		var oldW = $('input[name=width]').val()/st.h;
		var oldH = $('input[name=height]').val()/st.v;
		
		var newW = max(oldW, oldH);
		var newH = newW;
		
		if(newW*st.h > 300) {
			newW = 300/st.h;
			newH = newW;
		}
		if(newH*st.v > 300) {
			newW = 300/st.v;
			newH = newW;
		}

		if(newW*st.h > 150 && newH*st.v > 150) {
			newW = 150/min(st.v, st.h);
			newH = newW;
		}
		
		$('input[name=width]').val(newW*st.h);
		$('input[name=height]').val(newH*st.v);
		$('#newWidth').text(newW*st.h);
		$('#newHeight').text(newH*st.v);		
		
		updateFramePreview();
		updatePriceBox();
	}
}

function increaseSize(which) {
	changeSize(which, 5);
}

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

function changeSize(which, bywhat) {
	var styleNo = $('input[name=popstyle]').val();
	var st = styleOptions[styleNo];
	var oldW = $('input[name=width]').val()/st.h;
	var oldH = $('input[name=height]').val()/st.v;
	var isSquare = $('#input_square')[0].checked;
	
	//console.log(oldW, oldH);
	
	if(which == 'w') {
		var newW = oldW+bywhat;
		var newH = oldH;
		if(isSquare) newH = newW;
		if(newW*st.h < 20 || newH*st.v < 20) {
			newW = oldW;
			newH = oldH;
		}
		if(newW*st.h > 300 || newH*st.v > 300) {
			newW = oldW;
			newH = oldH;
		}
		if(newW*st.h > 150 && newH*st.v > 150) {
			newW = oldW;
			newH = oldH;
		}
	}
	else {
		var newW = oldW;
		var newH = oldH+bywhat;
		if(isSquare) newW = newH;
		if(newH*st.v < 20 || newW*st.h < 20) {
			newH = oldH;
			newW = oldW;
		}
		if(newH*st.v > 300 || newW*st.h > 300) {
			newH = oldH;
			newW = oldW;
		}
		if(newW*st.h > 150 && newH*st.v > 150) {
			newW = oldW;
			newH = oldH;
		}
	}
	
	$('input[name=width]').val(newW*st.h);
	$('input[name=height]').val(newH*st.v);
	$('#newWidth').text(newW*st.h);
	$('#newHeight').text(newH*st.v);
	
	updateFramePreview();
	updatePriceBox();
}

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

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

function updateBoxNumber() {
	var n = styleOptions[$('input[name=popstyle]').val()].p;
	var c = $('.collageImagesContainer .collageImageUploadBox').length;
	var d = n-c;
	
	while(d > 0) {
		addNewImageBox();
		d--;
	}
	while(d < 0) {
		removeLastImageBox();
		d++;
	}
}

function updatePriceBox2() {
	//var prices = calcPrice(imgWidth, imgHeight, $('input[name=popstyle]').val(), frameType);
	var w = imgWidth;
	var h = imgHeight;
	var s = $('input[name=popstyle]').val();
	var f = frameType;
	
	var r = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getPrice:popart', 'POST', 'w='+w+'&h='+h+'&f='+f+'&s='+s, updatePriceBox2Loader)
	r.send();
}

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

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).parents('.upload-container'));
		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).parent().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) {
	var box = uploader.box();

	box.find('.iframeBar').hide().prev().css('margin-bottom', '5px');
	box.find('.ProgBar').show();
	box.find('a.gradButton').text( deletePictureText ).unbind('click').click( function () { resetImageBox( $(this).parent().parent() ) } );
	var n = box.find(':checkbox')[0].name.substr(6);
	
	box.find('.emptyBar').hide();
	box.find('a.gradButton').text( deletePictureText ).unbind('click').click( function () {
		resetImageBox( $(this).parents('.upload-container'));
		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 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 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( function () {
		resetImageBox( $(this).parents('.upload-container'));
	}).show();
	box.find('.deleteBar').show();
	
	if(w/h > 128/70) box.find('img').css('width', '128px').css('margin-top', Math.round((72-(128*h/w))/2)+'px').parent().css('height', '75px');
	else box.find('img').css('height', '72px').css('margin-top', 0);
}

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

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

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

    $("textarea#wishes").focus(function() {  
        if ($(this).val()== box2_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 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');
}

