/**
 * Current version works only with 2 images per page
 */
function FlipImages(){
    var images = $('.flyerimage'); //first image as frontside, second as backside
    var front = $(images[0]);
    var back = $(images[1]);
	
	if(images.length == 0){
		var images = $('.previewimage'); //first image as frontside, second as backside
		var front = $(images[0]);
		var back = $(images[1]);
	}

    if(images.length >= 2){
        front.data('initialML', parseInt(front.css('marginLeft')));
        back.data('initialML', parseInt(back.css('marginLeft')));
    }

    /**
     * @private
     */
    function _initRotateButton(){
        $('#rotate_button').click(function(){
            if(front.hasClass('none')){
                // hide backside show frontside
                _rotate(back, front);
                return;
            }
            
			//console.log(back);
            if(back.hasClass('none')){
                // hide frontside show backside
                _rotate(front, back);
                return;
            }


        });
    }

    var _rotationStatus = false;

    /**
     * @private
     */
    function _rotate(from, to){
        //console.log(from);
        if(_rotationStatus) return;
        _rotationStatus = true;
        var margin =from.width()/2;
        var width=from.width();
        var height=from.height();
        var nextid = '#'+from.attr('change');
        var thisid = from.attr('id');

        from.stop().animate(
            {
                width:'0px',
                height:''+height+'px',
                marginLeft:margin + 'px',
                opacity:'0.5'
            },
            500, // duration
            '',
            function(){
                from.toggleClass('none');
                from.hide();

                if($(nextid).css('marginLeft') == (to.data('initialML') + 'px')) {
                    
                    $(nextid).css({
                        'width': '0px',
                        'marginLeft':margin + 'px',
                        'height':height+'px',
                        'opacity':'0.5'
                    });
                }

                $(nextid).stop().animate(
                    {
                        width:''+width+'px',
                        height:''+height+'px',
                        marginLeft: to.data('initialML') + 'px',
                        opacity:'1'
                    },
                    500, //duration
                    '',
                    function(){
                        to.toggleClass('none');
                        to.show();
                        _rotationStatus = false;
                    }
                );
            }
        );


    }

    return {
        initRotateButton:_initRotateButton
    }
}

$(document).ready(function()
{
    // http-server
    var http_server = $('link[rel="index"]').attr('href');
    var datepicker_url = $('link[rel="datepicker_url"]').attr('href');
	
    // Eingabebereiche öffnen und schliessen
    initSectionOpen();
	
    $('#datepicker').datepicker(
    {
        dateFormat: 'yy-mm-dd' ,
        onSelect: function(dateText) {
            window.location.href = datepicker_url + "partyDate/" + dateText
        },
        firstDay: 1 ,
        defaultDate: 0,
		changeMonth: true,
		changeYear: true
    });

    try{
        var _d = window.location.href;
        _d = _d.substr(_d.lastIndexOf('/')+1);
        var dt = $.datepicker.parseDate('yy-mm-dd', _d);
        $('#datepicker').datepicker('setDate', dt);
    }
    catch(e){}
	
    $.fn.tagName = function() {
        return this.get(0).tagName.toLowerCase();
    }

    var checkArray = new Array();
	
    // the accordeon sections are equipped with the icons etc.
    $('.sectionOpen').each( function(i){
        $(this).addClass('ui-helper-reset ui-state-default ui-corner-all');
        $(this).prepend('<span class="left ui-icon ui-icon-triangle-1-e"></span>');
        if ($(this).is('.obligatorySection'))
        {
            // the warning-icon is only added to sections with obligatory information
            $(this).append('<span class="left ml5 status ui-icon ui-icon-alert"></span>');
        }
        $(this).append('<span class="right ui-icon ui-icon-circle-plus"></span>');
        $(this).append('<div class="clear"></div>');
        $(this).hover(
            function () {
                $(this).removeClass('ui-state-default');
                $(this).addClass('ui-state-hover');
            },
            function () {
                $(this).addClass('ui-state-default');
                $(this).removeClass('ui-state-hover');
            }
            );
		
        $(this).click(function() {
            $(this).next().slideToggle('normal');
            $(this).children('span').toggleClass('ui-icon-triangle-1-e');
            $(this).children('span').toggleClass('ui-icon-triangle-1-s');
            $(this).children('span.right').toggleClass('ui-icon-circle-plus');
            $(this).children('span.right').toggleClass('ui-icon-circle-minus');
            //
            // checkInputs();
            //
            return false;
        });
		
    } );

    $('.sectionOpen:first').click(); // open first accordeon on startup
	
    $('.section').each( function(i){
        var subcheck = new Array();
        $(this).children('.checkInput').each( function(s){
            subcheck.push(0);
        });
		
        checkArray.push(subcheck)
    });

    // init flip images
    flipImages = new FlipImages();
    flipImages.initRotateButton();


    //////////////
	
    //  Funktionen
	
    function initSectionOpen()
    {
        $('.sectionOpen').next().hide();
    }
			

    function changeValue(obj,value)
    {
        obj.text(value);
    }

    // init overlay images
    $("img[rel]").overlay();

    // init regions dialog
    $('#regions_dialog').dialog({
        autoOpen:false,
        title:'Regions',
        resizable:false,
        modal:true,
        width:470,
        height:308,
        position:['center', 'center'],
        dialogClass:'selection-dialog selectors',
        open:function(){
            try{
                var dlg = $(this);
                var titleBar = dlg.prev('div.ui-dialog-titlebar:first');
                var target = dlg.children('div.cell').children('ul').children('li.checked');
                var ch = Math.ceil(dlg.height() / 2);
                var top = target.position().top;
                dlg.animate({scrollTop: top - titleBar.outerHeight() - ch}, 500);
            }
            catch(e){}
        }
    });

    $('#more_regions').click(function(){$('#regions_dialog').dialog('open');});

    // init musicstyles dialog
    $('#musicstyles_dialog').dialog({
        autoOpen:false,
        title:'Musicstyles',
        resizable:false,
        modal:true,
        width:490,
        height:308,
        position:['center', 'center'],
        dialogClass:'selection-dialog selectors',
        open:function(){
            try{
                var dlg = $(this);
                var titleBar = dlg.prev('div.ui-dialog-titlebar:first');
                var target = dlg.children('div.cell').children('ul').children('li.checked');
                var ch = Math.ceil(dlg.height() / 2);
                var top = target.position().top;
                dlg.animate({scrollTop: top - titleBar.outerHeight() - ch}, 500);
            }
            catch(e){}
        }
    });

    $('#more_musicstyles').click(function(){$('#musicstyles_dialog').dialog('open');});

    $('#years_dialog').dialog({
        autoOpen:false,
        title:'Years',
        resizable:false,
        modal:true,
        width:490,
        height:308,
        position:['center', 'center'],
        dialogClass:'selection-dialog selectors',
        open:function(){
            try{
                var dlg = $(this);
                var titleBar = dlg.prev('div.ui-dialog-titlebar:first');
                var target = dlg.children('div.cell').children('li.checked');
                var ch = Math.ceil(dlg.height() / 2);
                var top = target.position().top;
                dlg.animate({scrollTop: top - titleBar.outerHeight() - ch}, 500);
            }
            catch(e){}
        }
    });

    $('#more_years').click(function(){$('#years_dialog').dialog('open');});


    // overlay settings
    $.tools.overlay.conf.speed = 500;

    // init buttons
    $('a.ui_button').button();

    // biography toggle button
    $('.biography_toggle_button').click(function(){
        var $el = $('#artist_biography');
        $el.toggleClass('bio_collapsed');
        $el.toggleClass('bio_expanded');
        if($el.hasClass('bio_collapsed')){
            $('#biography_toggle_link').text('>>>');
        }
        else if($el.hasClass('bio_expanded')){
            $('#biography_toggle_link').text('<<<');
        }
    });

    // promotiontext toggle button
    $('.promotiontext_toggle_button').click(function(){
        var $el = $('#promotiontext');
        $el.toggleClass('promotiontext_collapsed');
        $el.toggleClass('promotiontext_expanded');
        if($el.hasClass('promotiontext_collapsed')){
            $('#promotiontext_toggle_link').text('>>>');
        }
        else if($el.hasClass('promotiontext_expanded')){
            $('#promotiontext_toggle_link').text('<<<');
        }
    });
    /*
    jQuery("#regionsTree")
	.jstree({
		core : {
			// core options go here 
		}
	});
    */		
    jQuery(function(){
        jQuery('ul.sf-menu').superfish();
    });
});
/**
 * @param string title Dialog title
 * @param string text Dialog text
 * @param function buttons_handler
 */
function showDialog(title, text, buttons_handler, close_handler){
    var rnd = '' + Math.random();
    var id = 'dialog_'+rnd.substr(2);
    var dialog = $('<div>').attr({
        'id':id,
        'style':'display:none; overflow:auto;'
    }).html(text);

    dialog.dialog({
        'title':title,
        'resizable':false,
        'modal':true,
        'width':400,
        'height': 150,
        close:function(){
            if(jQuery.isFunction(close_handler)) close_handler(arguments);
            var id = $(this).attr('id');
            $(this).dialog('destroy');
            $('#'+id).remove();
        },
        'buttons':{
            'Ok':function(){
                if(jQuery.isFunction(buttons_handler)) buttons_handler(arguments);
                var id = $(this).attr('id');
                $(this).dialog('close');
                $('#'+id).remove();
            }
        }
    });
}
