
$(document).ready(function() {

	// http://fancybox.net
	// popup in der fancybox ausgeben
	$("a.popup").fancybox({
		'autoScale'			: true,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'type'				: 'iframe',
		'width'				: 625,
		'height'			: 600,
		'autoDimensions'	: true,
                'titleShow': false
	});

	// Großbild in der fancybox ausgeben
	$("a[rel=fancybox]").fancybox({
		'type'				: 'image'
		,'titlePosition' 	: 'inside'
//		,'transitionIn'		: 'none'
//		,'transitionOut'		: 'none'
		,'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-outside">' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	}
	);

        $("a.fancybox").fancybox({
		'type'				: 'image'
		,'titlePosition' 	: 'inside'
//		,'transitionIn'		: 'none'
//		,'transitionOut'		: 'none'
		,'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-outside">' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	}
	);
	
	initPlaceholders();
	initSubjectArea();
});


/**
 * Methode um Formularfelder, die einen Standardtext enthalten, bei "onFocus" leer zu machen.
 * Bei "onBlur" wird der Standardtext wieder eingetragen.
 * Der Standardtext muss im Attribut placeholder="" vorhanden sein.
 * Formularfelder kommasepariert der Variablen "placeHoldersSelector" zuweisen.
 */
var initPlaceholders = function() {
    var placeHoldersSelector = '#fCallbackForm:name, #fCallbackForm:phone';
    $(placeHoldersSelector).each(function() {
        var str = 'placeholder';
        if(!(str in document.createElement('input'))) {
            var placeholder = $(this).attr(str);
            $(this).addClass(str)
                .val(placeholder)
                .focus(function() {
//		                    if($(this).val() == placeholder) {
                        $(this).val('');
                        $(this).removeClass(str);
//		                    }
            }).blur(function() {
                if($(this).val() == '') {
                    $(this).addClass(str);
                    $(this).val(placeholder);
                }
            });
        }
    });
}


/**
* Höhe der Subject-Elemente auf der Startseite angleichen
*/
function initSubjectArea(){
	/* Variable zum Merken der maximalen Höhe */
	var max_height = 0;
	if($('#SubjectAreaNew')){
		$('#SubjectAreaNew .subject_grey_light').each(function(e){
			h = $(this).height();
			if(typeof(h) != "undefined") {
				if(h > max_height) {
					max_height = h;
				}
			}
		});
		if(max_height > 0) {
				$('#SubjectAreaNew .subject_grey_light').height(max_height);
		}
	}
} 


/**
 * PDF zum Bestellzettel hinzufügen
 * @param item
 */
function addItemToDownloadsCart(item) {
    jQuery.getJSON('downloadCartService.php', {action: 'add', item: item}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function removeItemFromDownloadsCart(item, mode) {
    jQuery.getJSON('downloadCartService.php', {action: 'remove', item: item, mode: mode}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function showDialog(id, cb) {
    width = (id == 'image_layer') ? 716 : 694;
    dialogClass = (id == 'image_layer') ? 'image_dialog' : '';
    if($('#'+id).length == 0) {
            $('body').append('<div id="'+id+'"></div>');
            var options = {
                autoOpen: false,
                modal: true,
                resize: false,
                width: width,
                title: false,
                draggable: false,
                stack: true,
                closeText: '',
                dialogClass: dialogClass,
                height: 'auto',
                open: function(){closedialog=1;$(document).bind('click', function(){if(closedialog){$('#'+id).dialog('close');}closedialog=1;});},
                focus: function(){closedialog = 0;},
                close: function(){$(document).unbind('click');},
                position: ['center',175]
            }
            if($.browser.msie && $.browser.version=='6.0') {
                // IE6 does not work well with modal in this case:
                options.modal = false;
            }
            $('#'+id).dialog(options);
        } else {
            $('#'+id+'_content').html('');
            //$('#'+id).dialog('open');
        }
        dialog = $('#'+id).dialog('open');
        closedialog = 0;
        var htmlContent = '';
        jQuery.post('index.php', {"layer:id": id, template: '99_layer.html'}, function(data) {
            htmlContent = data;
            if($.browser.msie && $.browser.version=='6.0') {
            // IE6 does not work well with modal in this case:
            //htmlContent = '<div id="'+id+'_content"></div>';
            }
            $('#'+id).html(htmlContent);
            if(typeof cb == 'function') {
                cb();
            }
        });
//        var htmlContent = '<div class="close_label"><a href="#" onClick="$(\'#'+id+'\').dialog(\'close\');return false;">schliessen <img src="project/media/images/layer_close.gif" /></a></div>'
//            +'<div id="'+id+'_content"></div>';
        
}

function showDownloadsCart(mode) {
        showDialog('download_cart_layer', function() {
            getDownloadsCartContent(mode);
        });
	//contentNode = document.getElementById("overlayContainerContent");
	//contentNode.innerHTML = '<div style="width:100%; text-align:center; margin:auto; margin-bottom:50px;"><img src="project/media/images/loading.gif" border="0" /></div>';
	
}

function showImage(file) {
    showDialog('image_layer', function() {
        $('#image_layer_content').html('<img src="'+file+'" />');
    });
}

function getDownloadsCartContent(mode) {
    jQuery.getJSON('downloadCartService.php', {action: 'get', mode: mode}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function updateDownloadsCart(item, num, mode) {
    jQuery.getJSON('downloadCartService.php', {action: 'update', item: item, num: num, mode: mode}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function showDownloadCartForm() {
    showDialog('download_cart_layer', function() {
        displayContent('index.php?pageID=cartform&template=11_cart_form_single.html', 'download_cart_layer_content');
    });
}
/*
$('document').ready(function(){
    $('img').each(function(){
        if($(this).attr('orig_src')) {
            resizeImage($(this));
        }
    });
});
*/
function resizeImage(elem, cb) {
    var origWidth = elem.attr('orig_width');
    var ratio = elem.parent().width() / origWidth;
    var newWidth = '';
    if(elem.closest('div').hasClass('borderImage')) {
        newWidth = elem.closest('div').width() - 2;
        //console.log(elem.closest('div').dimensions);
    }
    else {
        newWidth = Math.round(elem.closest('div').width());
    }
    var height = '';
    if(elem.attr('resizeHeight') == 'true') {
        height = elem.parent().height();
        newWidth = newWidth-2;
    }
    var squareImage = 'false';
    if(elem.attr('square_image') == 'true') {
        squareImage = 'true';
        newWidth = newWidth-3;
    }
    //elem.attr('src', 'image.php?file='+elem.attr('orig_src')+'&width='+newWidth);
    var that = elem;
    console.log('http://products.comfosystems.de/image.php?file='+elem.attr('orig_src')+'&width='+newWidth+'&height='+height+'&squareImage='+squareImage);
    jQuery.get('http://products.comfosystems.de/image.php?file='+elem.attr('orig_src')+'&width='+newWidth+'&height='+height+'&squareImage='+squareImage, function(data){
        console.log(data);
        that.attr('src', data);
        if(typeof cb == 'function') {
            cb();
        }

    });
    elem.closest('div.contentImage').children('map').find('area').each(function() {
        var coords = $(this).attr('coords');
        coords = coords.split(',');
        var newCoords = '';
        for(var i=0;i<coords.length;i++) {
            newCoords += ratio * coords[i];
            if(i+1 < coords.length) newCoords += ',';
        }
        $(this).attr('coords', newCoords);
    });

    elem.nextAll('div.imagemap_area').each(function() {
       $(this).css('top', ratio * $(this).position().top+'px');
       $(this).css('left', ratio * $(this).position().left+'px');
       $(this).css('width', ratio * $(this).width()+'px');
       $(this).css('height', ratio * $(this).height()+'px');
    });

}
