var iSubMenu = 0;
var iMenu = 0;

$(document).ready(function(){
    // **************************************************
    // handle mouseover for navigation elements
    // **************************************************
    ///
    $('a img').mouseover(function(){
        if (this.id != '') {
            if (iSubMenu == 0) {
                iMenu = this.id;
            }
            
            var img = (this.src).replace('_de', '_ak');
            this.src = img;
            
            if (this.className != "" || this.className != undefined) {
                var mcid = this.className.substring(this.className.indexOf('mcid__') + ('mcid__').length);
                mcid = mcid.substring(0, mcid.indexOf(' '));
                
                if (mcid != 0) {
                    iSubMenu = this.id;
                    var data = $('a img').offset();
                    $('ul#sub_' + this.id).fadeIn(100);
                }
                else {
                    if ($(this).closest('ul').attr('id') != ("sub_" + iSubMenu)) {
                        if (iMenu == iSubMenu) {
                            if (($('#' + iMenu).attr('id')).indexOf('ak_') == -1) {
                                var img = $('#' + iMenu).attr('src').replace('_ak', '_de');
                                $('img#' + iMenu).attr('src', img);
                            }
                        }
                        
                        $('ul#sub_' + iSubMenu).fadeOut(20);
                        iSubMenu = 0;
                    }
                }
            }
        }
    });
    
    
    // **************************************************
    // handle mouseout for navigation elements
    // **************************************************
    ///
    $('a img').mouseout(function(){
        if (this.id != '') {
            if ((this.id).indexOf('ak_') == -1) {
                if (iSubMenu != 0 && iMenu != this.id && iSubMenu != this.id) {
                    var img = (this.src).replace('_ak', '_de');
                    this.src = img;
                }
                
                if (iSubMenu == 0) {
                    var img = (this.src).replace('_ak', '_de');
                    this.src = img;
                }
            }
        }
    });    
    
    
    // **************************************************
    // identify image as button
    // **************************************************
    ///
    $('#imgednew #upload').mouseover(function(){
        this.style.cursor = 'pointer';
    });
    
    $('#save').mouseover(function(){
        this.style.cursor = 'pointer';
    });
    $('#contentsave').mouseover(function(){
        this.style.cursor = 'pointer';
    });
    
    $('#tbl_img img').mouseover(function(){
        if (this.id != '') {
            this.style.cursor = 'pointer';
        }        
    });
    
    $('#tbl_cat img').mouseover(function(){
        if (this.id != '') {
            this.style.cursor = 'pointer';
        }        
    });    
    
    $('#image2 div.block omg').mouseover(function(){
        if (this.id != '') {
            this.style.cursor = 'pointer';
        }        
    });    
    
    
    // **************************************************
    // handle galery export
    // ..................................................
    // **************************************************
    ///
    $('#pub-gal').mouseover(function(){
    	this.className = 'pub-gal-hover';
    });
    
    $('#pub-gal').mouseout(function(){
    	this.className = 'pub-gal-out';
    });
    
    $('#pub-gal').click(function(){
    	var mid = $('#id').val();
        var mcid = $('#cid').val();

        $.ajax({
    		type: 'GET',
            url: 'handleData.php',	
            data: 'do=export_gal&mid=' + mid + '&mcid=' + mcid, 
            success: function(phpData){
    			if(phpData == 1) {    				
    				$("#gal-compl").html('Die Daten wurden erfolgreich exportiert.');
    				$("#gal-compl").fadeIn('slow');
    				
    				t = setTimeout(function(){
    					$("#gal-compl").css('display', 'none');
    				}, 2500);
    			}
    			else {    				
    				ret = phpData;
    			}        		       	
        	}
    	});
    	return false;
    });
    
    $('#pub-gal').submit(function(){
        var mid = $('#id').val();
        var mcid = $('#cid').val();
        //alert("HIER")
    	$.ajax({
    		type: 'GET',
            url: 'handleData.php',	
            data: 'do=export_gal&mid=' + mid + '&mcid=' + mcid, 
            success: function(phpData){
    			if(phpData == 1) {
    				$("#gal-compl").html('Die Daten wurden erfolgreich exportiert.');
    				$("#gal-compl").fadeIn('slow');
    				
    				t = setTimeout(function(){
    					$("#gal-compl").css('display', 'none');
    				}, 2500);
    			}
    			else {
    				ret = phpData;
    			}        		       	
        	}
    	});
    	return false;
    });
    
    // **************************************************
    // handle references
    // ..................................................
    // **************************************************
    //    
    $('#image2 div.block img').click(function(){     
        var mid = $('#id').val();
        var mcid = $('#cid').val();

        var ret = 1;
        
        for(var i = 0; i < 4; i++){  
            var contid = $('#id_' + i).val();
            var contval = $('#txt_' + i).val();
            contval = contval.replace(/\n/g, '<br />');
            //contval = contval.replace(/&/g, 'uUu');
            //contval = contval.replace(/\+/g, 'aUa');

            if(ret == 1){
	        	$.ajax({
	                type: 'GET',
	                url: 'handleData.php',
	                data: 'do=ref_save&mid=' + mid + '&mcid=' + mcid + '&contid=' + contid + '&contval=' + encodeURIComponent(contval) + '&act=ref',
	                success: function(phpData){
	        		    if(phpData == 1) {
	        		    }
	        		    else {
	        		    	ret = phpData;
	        		    }        		       	
	                }
	            });  
        	}
        }   
        
        if(ret == 1){
        	alert("Daten wurden gespeichert");
        }
        
        //$('#frm').submit();             
    });
    
    /** **************************************************
     handle category link (edit, delete, position)
     blend edit field
     ..................................................
     **************************************************
     */
    $('table#tbl_img img').click(function(){
        var type = (this.id).substr(0, (this.id).indexOf('_'));
        var id = (this.id).substr((this.id).indexOf('_') + 1);
        var im_title = $('#im_title').val();
        
        if ($('#imgednew').is(':visible') == true) {
            $('#imgednew').fadeOut(200);
        }
        
        switch (type) {
            case 'new':
            case 'edit':
                $('#imgednew fieldset legend#tit').html((type == 'new') ? 'Neu' : 'Bearbeiten');
                $('#imgednew fieldset #im_title').attr('value', (type == 'new') ? '' : $('#title_' + id).val());
                $('#imgednew fieldset #meta_tags').attr('value', (type == 'new') ? '' : $('#tags_' + id).val());
                $('#imgednew fieldset #meta_desc').attr('value', (type == 'new') ? '' : $('#desc_' + id).val());
                $('#imgednew fieldset #s_cont').attr('value', (type == 'new') ? '' : id);
                $('#imgednew').fadeIn(200);
                break;
            case 'up':
            case 'down':
                handleCatImg('img', type, im_title, id);
                break;
            case 'del':
                handleCatImg('img', type, im_title, id);
                break;
        }
    });
    
    
    /** **************************************************
     handle category link (edit, delete, position)
     blend edit field
     ..................................................
     **************************************************
     */
    $('table#tbl_cat img').click(function(){
        var type = (this.id).substr(0, (this.id).indexOf('_'));
        var id = (this.id).substr((this.id).indexOf('_') + 1);
        
        if ($('#catednew').is(':visible') == true) {
            $('#catednew').fadeOut(200);
        }
        
        switch (type) {
            case 'new':
             case 'edit':
                $('#catednew fieldset legend').html((type == 'new') ? 'Neu' : 'Bearbeiten');
                $('#catednew fieldset #s_title').attr('value', (type == 'new') ? '' : $('#txt_' + id).val());
                $('#catednew fieldset #s_cat').attr('value', (type == 'new') ? 0 : id);
                $('#catednew').fadeIn(200);
                break;
            case 'up':
            case 'down':
                handleCatImg('cat', type, '', id);
                break;
            case 'del':
                var check = confirm('Alle Bilder und Inhalte werden entfernt.\nWollen Sie die Kategorie wirklich löschen?');
                
                if (check == true) {
                	handleCatImg('cat', type, '', id);
                }
                
                break;
        }
    });
    
    /** **************************************************
     save new or changed category
     ..................................................
     **************************************************
     */
    $(function(){
        $('#catednew img').click(function(){
            newUpdateCatImg('cat', this.id);
            return false;
        });
        
        $('#imgednew img').click(function(){
            newUpdateCatImg('img', this.id);
            return false;
        });
        
        var btnUpload = $('#upload');
        var status = $('#err');
        
        new AjaxUpload(btnUpload, {
            type: 'GET',
            action: 'handleData.php',
            //Name of the file input box
            name: 'uploadfile',
            data: {
                'i_cat': $('#i_cat').val(),
                'mid': $('#id').val(),
                'mcid': $('#cid').val(),
                'cat': $('#cat').val(),
                'do': 'img_save'
            },
            onSubmit: function(file, ext){
                if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                    // check for valid file extension
                    status.text('Nur JPG, PNG oder GIF Dateien sind erlaubt.');
                    return false;
                }
                
                status.text('Datei wird hochgeladen...');
            },
            onComplete: function(file, response){
                //On completion clear the status
                status.text('');

                //Add uploaded file to list
                if (response == 1) {
                    status.text('Datei wurde erfolgreich hochgeladen.');
                    $('#frm').submit();
                }
                else {
                    status.text(response);
                }
            }
        });
    });
    

    /** **************************************************
     save new or changed image title
     ..................................................
     **************************************************
     */
    function newUpdateCatImg(type, idselect){
        var s_title = (type == 'cat') ? encodeURIComponent($('#s_title').val()) : encodeURIComponent($('#im_title').val());
        var mid = $('#id').val();
        var mcid = $('#cid').val();
        var cont = (type == 'cat') ? '' : encodeURIComponent($('#s_cont').val());
        var tags = (type == 'cat') ? '' : encodeURIComponent($('#meta_tags').val());
        var desc = (type == 'cat') ? '' : encodeURIComponent($('#meta_desc').val());
        var cat = (type == 'cat') ? encodeURIComponent($('#s_cat').val()) : encodeURIComponent($('#cat').val());

        if (idselect != '') {
          if (idselect == 'save') {
                $.ajax({
                    type: 'GET',
                    url: 'handleData.php',
                    data: 'do='+type+'_save&mid=' + mid + '&mcid=' + mcid + '&cont=' + cont + '&s_title=' + s_title + '&cat=' + cat + '&tags=' + tags + '&desc=' + desc,
                    success: function(phpData){  
                        if (phpData != 1) {
                            switch(type){
                                case 'cat':
                                    $('#catednew p#err').html(phpData);
                                break;
                                case 'img':
                                    $('#imgednew p#err').html(phpData);
                                break;
                            }
                        }
                        else {
                            $('#frm').submit();
                        }
                    }
                });
          }
        }
    }

    
    /** **************************************************
     set and handle events for edit category/image -
     position up and down, delete and edit
     ..................................................
     @param  type - event type
     id - id selected category
     @return /
     **************************************************
     */
    function handleCatImg(type, handle, title, id){
        var mid = $('#id').val();
        var mcid = $('#cid').val();
        var cat = (type == 'cat') ? id : $('#cat').val();
        
        $.ajax({
            type: 'GET',
            url: 'handleData.php',
            data: 'do=' + type + '_' + handle + '&mid=' + mid + '&mcid=' + mcid + '&cat=' + encodeURIComponent(cat) + '&im_title=' + encodeURIComponent(title) + '&cont=' + encodeURIComponent(id),
            success: function(phpData){
                if (phpData != 1) {
                    alert(phpData);
                }
                else {
                    $('#frm').submit();
                }
            }
        });
    }
});
