$(document).ready(function() {
    if ($('#fotoplus ol').length > 0) {
        $('#fotoplus ol li').attr('class', function(index) {
            return 'item-' + index;
        });
    }
    if ($('#uploadSubmitter').length > 0) {
    	$('#uploadSubmitter.submit').hide();

    	$('#uploadSubmitter').click(function() {
    		$('#uploadOverlay').css('display', 'block');
    		if (!window.innerWidth && !window.innerHeight) {
    			$('#uploadOverlay').css('height', document.body.offsetHeight);
    			$('#uploadOverlay').css('width', document.body.offsetWidth);
    		}
    	});
    }

    if ($('#uploadedFiles').length > 0) {
        var uploadedFiles      = $('#uploadedFiles').val();
        var uploadedFilesArray = uploadedFiles.split(',');

        $('#upload > .uploadFormWrapper').hide();
        switch (uploadedFilesArray.length) {
            case 1:
            case 2:
            case 3:
                for (var i=0; i<uploadedFilesArray.length; i++) {
                    switch (uploadedFilesArray[i]) {
                        case '':
                        case 'IMG_DIM_ERROR':
                            $('#upload > .wrapper' + (i+1)).show();
                            break;
                        default:
                            $('#upload > .wrapper' + (i+1)).hide();
                            $('#upload > .wrapper' + (i+2)).show();
                    }
                }
                break;
            case 0:
            default:
                $('#upload > .wrapper1').show();
        }
        /*
        if (uploadedFilesArray.length > 0 && uploadedFilesArray[0] != '') {
            for (var i=0; i<uploadedFilesArray.length; i++) {
                if (uploadedFilesArray[i] != 'IMG_DIM_ERROR') {
                    $('#upload > .wrapper' + (i+1)).hide();
                }
            }
            switch (uploadedFilesArray.length) {
                case 1:
                    if (uploadedFilesArray[0] != 'IMG_DIM_ERROR') {
                        $('#upload > .wrapper1').hide();
                    }
                    break;
                case 2:
                    $('#upload > .wrapper1').hide();
                    $('#upload > .wrapper2').hide();
                    break;
                case 3:
                    $('#upload > .wrapper1').hide();
                    $('#upload > .wrapper2').hide();
                    $('#upload > .wrapper3').hide();
                    break;
            }
        }
        */
    }

	$('#uploadInformation').accordion({
		header: 'div.commonInfo',
		active: false,
		autoheight: false,
		alwaysOpen: false
	});

	$("#searchInput").autocomplete(
        "index.php?eID=fotoplus_autocomplete",
        {
            minChars:       3,
            matchSubset:    1,
            matchContains:  1,
            cacheLength:    0,
            onItemSelect:   selectItem,
            maxItemsToShow: 32,
            width:          290,
            formatItem:     formatItem,
            selectOnly:     1
        }
    );

        // popup integration
	$('.addVariation').click(function() {
		var popup = openCenteredWindow(popupUrl, "popup", 664, 374, "directories=no, toolbar=no, location=no, menubar=no, status=no, resizable=no, dependent=no, scrollbars=no");
		popup.focus();
	});
    /*
        // layer integration
    $('.addVariation').click(function (e) {
		e.preventDefault();
		$('#modalContainer').modal({
			onShow: loadModalContent(popupUrl),
			onClose: function (dialog) {
				dialog.data.hide();
				dialog.container.hide();
				dialog.overlay.hide();
				// must call this to have SimpleModal re-insert the data correctly and clean up the dialog elements
				$.modal.close();
			}
		});
	});
    */

    $('.conditionsLink').click(function (e) {
		e.preventDefault();
		$('#modalContainer').modal({
			onShow: loadModalContent($(this).attr('href')),
			onClose: function (dialog) {
				dialog.data.hide();
				dialog.container.hide();
				dialog.overlay.hide();
				// must call this to have SimpleModal re-insert the data correctly and clean up the dialog elements
				$.modal.close();
			}
		});
	});

	if ($('#variations dl').length) {
		$('.addVariation').hide();
		refreshItems();
	} else {
		$('#variationSubmit').hide();
	}

	$('#orderList').accordion({
		header: 'div.commonInfo',
		active: false,
		autoheight: false,
		alwaysOpen: false
	});

	if ($('#userInfoErrors').attr('value') == 'false') {
		helpLabelStandard = '';
		$('#helpContainer').remove();
		$('#helpContainerHead').remove();
	} else {
		$('#helpContainer').html(helpLabelStandard);
	}

	$('#userForm .radio').click(function() {
		if ($('#conditionsAccepted').attr('value') == 'false') {
			simulateClick('usageConditionsLink');
		}
	});
});

function insertVariation(material, model, color, pattern, accessories) {
	var itemCount = $('#variations dl').length;

	if (itemCount >= 0) {
		$('#variationSubmit').show();
	}

	if (itemCount >= 2) {
		$('.addVariation').hide();
	}

	if (itemCount >= 3) {
		alert(errVarLabel);
		return false;
	} else {
		if (accessories == '@Accessories@') {
			accessories = '&nbsp;';
		}
		var legendHtml	    = '<dt class="legend">Dach ' + (itemCount+1) + '</dt><dd class="legend"><span class="delete">' + delVarLabel + '</span>&nbsp;</dd>';
		var materialHtml	= '<dt>' + materialLabel	+ ':</dt><dd>' + material + '&nbsp;</dd>';
		var modelHtml		= '<dt>' + modelLabel		+ ':</dt><dd>' + model + '&nbsp;</dd>';
		var colorHtml		= '<dt>' + colorLabel		+ ':</dt><dd>' + color + '&nbsp;</dd>';
		var patternHtml		= '<dt>' + patternLabel		+ ':</dt><dd>' + pattern + '&nbsp;</dd>';
		var accessoriesHtml	= '<dt>' + accessoriesLabel	+ ':</dt><dd>' + accessories + '&nbsp;</dd>';
		var variationHtml	= legendHtml + materialHtml + modelHtml + colorHtml + patternHtml + accessoriesHtml;

		var variationValue	= trim(material) + '###' + trim(model) + '###' + trim(color) + '###' + trim(pattern) + '###' + trim(accessories);
		var variationInput	= '<input type="hidden" name="tx_tefotoplus_pi1[variations][]" value="' + variationValue + '" />';

		$('#variations').append('<dl>' + variationHtml + variationInput + '</dl>');

		refreshItems();
	}
}

function insertAcceptStatus(valueAccept) {
	if (valueAccept != 'true' && valueAccept != 'false') {
		valueAccept = 'false';
	}

	$('.conditionsAccepted').attr('value', valueAccept);
	$('.conditionsAccepted').attr('checked', true);
}

function refreshItems() {
    var itemCount = $('#variations dl').length;

	$('#variations dl span.delete').unbind('click');
	$('#variations dl span.delete').click(function() {
		$(this).parent('dd').parent('dl').remove();
        refreshItems();
	});

    // if no variation is selected yet:
    // hide the submit button and
    // change the addVariation-text
    if (itemCount <= 0) {
        $('#variationSubmit').hide();
        $('.addVariation').html();
    } else {
        $('#variations dl dt.legend').each(function(index) {
            $(this).html('Dach ' + (index+1));
        });
    }

    // if less than 3 variations are selected, then show the addVariation-text
    if (itemCount < 3) {
        $('.addVariation').show();
    }
}

function openCenteredWindow(url,winName,winWidth,winHeight,winParams)	{
    // coords to center popup
    var newX, newY;
    newX = (screen.width - winWidth) / 2;
    newY = (screen.height - winHeight) / 2;

    // check user resolution to center the popup
    if (screen.width > winWidth) {
        if (screen.height > winHeight) {
            newWinParams = winParams + ',width=' + winWidth + ',height=' + winHeight + ',left=' + newX + ',top=' + newY;
        }
        else {
            newWinParams = winParams + ',width=' + winWidth + ',height=' + screen.height + ',left=' + newX + ',top=0,scrollbars=yes';
        }
    }
    else {
        if (screen.width <= winWidth) {
            if (screen.height <= winHeight) {
                newWinParams = winParams + ',width=' + screen.width + ',height=' + screen.height + ',left=0,top=0,scrollbars=yes';
            }
            else {
                newWinParams = winParams + ',width=' + screen.width + ',height=' + winHeight + ',left=0,top=' + newY + ',scrollbars=yes';
            }
        }
    }

    var ppWindow = window.open(url,winName,newWinParams);
	if (ppWindow) {
        ppWindow.focus();
    }

    return ppWindow;
}

function loadModalContent(url) {
	var mC = $('.modalContent');
	$(mC).html('<iframe src="'+url+'" height="374" width="664" frameborder="0" scrolling="no"></iframe>');
}
function closeModal() {
    $.modal.close();
}


// functions for autocompletion
function selectItem(li) {
	document.getElementById("searchInput").focus()
}

function formatItem(row) {
	return row[0];
}

// function for trimming whitespaces
function trim (string) {
	if (typeof(string) != 'undefined') {
  		return string.replace (/^\s+/, '').replace (/\s+$/, '');
	} else {
		return '';
	}

}


function simulateClick(elId) {
	var evt;
	var el = document.getElementById(elId);
	if (document.createEvent) {
		evt = document.createEvent("MouseEvents");
		if (evt.initMouseEvent)	{
			evt.initMouseEvent("click", true, true, window,
			0, 0, 0, 0, 0, false, false, false, false, 0, null);
		} else {
			evt = false;
		}
	}
	(evt)? el.dispatchEvent(evt):(el.click && el.click());
}
