var selected_itemtype_id = 0;
var server_id = "updates";
var current_pmid = 0; //JS Plugin Editor
var item_id = 0;
var script_id = "";




/**
* 
* 
* BASE
* 
* 
* 
*/

/**
* show a dialog
*/
function ppm_dialog_display(div, height, width, open_function, buttons, title, context_trigger){
    //set_dialog_title(div, open_function);

    //alert(open_function);
    
    //Defauls
    if (typeof div == "undefined") div = "dialog";
    if (typeof height == "undefined") height = 300;
    if (typeof width == "undefined") width = 300;

    $('#'+div).dialog({
        autoOpen: true,
        modal: true,
        width: width,
        height: height,
        //show: 'fade',
        title: title,

           buttons: buttons,

        open: function(event, ui) {
            if (typeof open_function != "undefined"){
                add_ajax_loader(div);
                open_function(div);
            }
        }
   });
}


function add_ajax_loader(div){
    var loader_img = '<img src="http://www.pagepipe.org/layouts/pagepipe/css/ui/ui-darkness/images/ajax-loader.gif" style="padding:10px 0 0 10px;">';
    $('#'+div).html(loader_img);
}

function show_status(status){
    if($('#pm_status').is(':visible')){
        $('#pm_status').fadeOut(function(){
            $('#pm_status').html(status);
            $('#pm_status').fadeIn();
        });
    }
    else{
        $('#pm_status').html(status);
        $('#pm_status').fadeIn();
    }
    hide_success_message();
}

function hide_success_message(){
    window.setTimeout("do_hide_success_message()", 1500);
}

function do_hide_success_message(){
    $('#success_message').slideUp();
}


/**
* get postable parameters from a form
*/
function get_form_params(form_id){

    var params = {};
    
    //all fields except radio inputs and multiple checkboxes
    $("#"+form_id + " input, #"+form_id + " select, #"+form_id + " textarea").each(function(){
        if ($(this).attr('type') != "radio"){
            var value = $(this).val();
            var name = $(this).attr('name');

            if ($(this).attr('type') == "checkbox"){
                if ($(this).attr('checked') && name.search(/\[/) == -1) params[name] = value;
            }
            else params[name] = value;
        }
    });

    //now the radio inputs and multiple checkboxes    
    $("#"+form_id + " input").each(function(){
        var value = $(this).val();
        var name = $(this).attr('name');

        if ($(this).attr('type') == "checkbox" && name.search(/\[/) != -1){

            if ($(this).attr('checked')){
                name = name.replace(/\[\]/g, '');
                if (!params[name]) params[name] = {};
                params[name].push(value);
            }
        }

        if ($(this).attr('type') == "radio"){
            if ($(this).attr('checked')) params[name] = value;
        }
    });

    return params;
  }

function ppm_save(script, func, form_id, callback){

    var params = get_form_params(form_id);
    params['function'] = func;

    //console.log(base_url+"/modules/ajax.php");
    //return false;
    
    $.post(base_url+"/modules/ajax.php", params,
        function(answer){
            if (callback && typeof(callback) === "function") callback();

            if (answer.status != '') show_status(answer.status);
        }
    , "json");   
}  



function in_array(needle, haystack){
	
	if (haystack == null) return false;
	if (typeof haystack == 'undefined') return false;
	for(i=0;i<haystack.length;i++){		
		if (haystack[i] == needle) return true;
	}
	return false;
}

function to_textarea(aTag, formfield) {
 
  var input = document.getElementById(formfield);
  var eTag = "";
  
  input.focus();
  /* f�r Internet Explorer */
  if(typeof document.selection != 'undefined') {
    /* Einf�gen des Formatierungscodes */
    var range = document.selection.createRange();
    var insText = range.text;
    range.text = aTag + insText + eTag;
    /* Anpassen der Cursorposition */
    range = document.selection.createRange();
    if (insText.length == 0) {
      range.move('character', -eTag.length);
    } else {
      range.moveStart('character', aTag.length + insText.length + eTag.length);      
    }
    range.select();
  }
  /* f�r neuere auf Gecko basierende Browser */
  else if(typeof input.selectionStart != 'undefined')
  {
    /* Einf�gen des Formatierungscodes */
    var start = input.selectionStart;
    var end = input.selectionEnd;
    var insText = input.value.substring(start, end);
    input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
    /* Anpassen der Cursorposition */
    var pos;
    if (insText.length == 0) {
      pos = start + aTag.length;
    } else {
      pos = start + aTag.length + insText.length + eTag.length;
    }
    input.selectionStart = pos;
    input.selectionEnd = pos;
  }
  /* f�r die �brigen Browser */
  else
  {
    /* Abfrage der Einf�geposition */
    var pos;
    var re = new RegExp('^[0-9]{0,3}$');
    while(!re.test(pos)) {
      pos = prompt("Einf�gen an Position (0.." + input.value.length + "):", "0");
    }
    if(pos > input.value.length) {
      pos = input.value.length;
    }
    /* Einf�gen des Formatierungscodes */
    var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
    input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
  }
}




function make_star_rating_item(div){		

	$('input[@jtype=item_rating].star').rating({callback: function(value, link){
		
		//Hier der Post rein f�r Speicherung
		//UserId, Timestamp, ItemID
		//Ein User kann nur einmal f�r ein Item voten
		var item_id = $('#'+div).attr('item_id');
		
		$.post("../../modules/js_events/js_events_global.php", { 'form': 'item_rating', 'item_id':item_id, 'value':value }, function(status){
			if (status == "ok"){
				$('#'+div).fadeOut(500, function(){
					$('#'+div).html($("#rating_done_ok").html());
					$('#'+div).fadeIn(500);
				});			
			}
			else if(status == "corrected"){
				$('#'+div).fadeOut(500, function(){
					$('#'+div).html($("#rating_done_corrected").html());
					$('#'+div).fadeIn(500);
				});			
			}
			else{
				alert('failed to save');
			}

		});							
	}});	

}


function make_star_rating_user(div){		

	$('input[@jtype=user_rating].star').rating({callback: function(value, link){
		
		//Hier der Post rein f�r Speicherung
		//UserId, Timestamp, ItemID
		//Ein User kann nur einmal f�r ein Item voten
		var to_user_id = $('#'+div).attr('to_user_id');
		
		$.post("../../modules/js_events/js_events_global.php", { 'form': 'user_rating', 'to_user_id':to_user_id, 'value':value }, function(status){
			if (status == "ok"){
				$('#'+div).fadeOut(500, function(){
					$('#'+div).html($("#rating_done_ok").html());
					$('#'+div).fadeIn(500);
				});			
			}
			else if(status == "corrected"){
				$('#'+div).fadeOut(500, function(){
					$('#'+div).html($("#rating_done_corrected").html());
					$('#'+div).fadeIn(500);
				});			
			}
			else{
				alert('failed to save');
			}

		});							
	}});	
}




function check_new_messages(){
	$.get("../../modules/js_events/js_events_global.php?action=check_new_messages", function(data){
		
		if (data == "new_messages"){
			$('#new_messages').bind("click", function(){ document.location.href='?page=message_inbox';});
			$('#new_messages').fadeIn(2000);
		}
		else{
			$('#new_messages').fadeOut();
		}
	});

	window.setTimeout("check_new_messages()", 15000);
}



function save_textblock(id){
	 	$('#'+id).html('<textarea id="input_'+id+'" style="border:1px solid #000;width:99%;height:100px">'+$('#'+id).html()+'</textarea>'+'<br /><input type="button" value="speichern" id="save_textblock_'+id+'">');
	 	$('#'+id).unbind("click");
	 	$('#input_'+id).focus();



		$('#save_textblock_'+id).bind("click", function(e){

			$.post("../../modules/js_events/js_events_admin.php", { 'form': 'textblock', 'id': $('#'+id).attr('textblock_id'), 'content': $('#input_' + id).val(), 'langid': $('#'+id).attr('langid') }, function(status){
				if (status == "ok"){
					$('#'+id).html($('#input_'+id).val());
					
					$('#'+id).bind("click", function(e){
						save_textblock(id);
					})

				}
				else{
					alert('failed to save');
				}
			});

		})

}


function save_textblockname(id){
	 	$('#'+id).html('<textarea id="inputname_'+id+'" style="border:1px solid #000;width:99%;height:18px">'+$('#'+id).html()+'</textarea>'+'<br /><input type="button" value="speichern" id="save_textblock_'+id+'">');
	 	$('#'+id).unbind("click");
	 	$('#input_'+id).focus();

		$('#save_textblock_'+id).bind("click", function(e){

			$.post("../../modules/js_events/js_events_admin.php", { 'form': 'textblockname', 'id':id, 'content': $('#inputname_' + id).val() }, function(status){
				if (status == "ok"){
					var val = $('#inputname_'+id).val();
					$('#'+id).html(val);
					$('#link_'+id).html('&#123;tb id='+val+'&#125;');
					
					$('#'+id).bind("click", function(e){
						save_textblockname(id);
					})
				}
				else{
					alert('failed to save');
				}
			});
		})
}


function ajax_loader(id){
	$("#"+id).html('<img src="http://pagepipe.de/layouts/pagepipe/images/icons/ajax-loader.gif" />');
}


function var_dump( c ){
	if(jQuery.browser.mozilla) console.log( c );
}

function email_valid(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	var check=true;
	if (str.indexOf(at)==-1){
		check=false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		check=false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		check=false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		 check=false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		 check=false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		 check=false;
	 }
	
	 if (str.indexOf(" ")!=-1){
		 check=false;
	 }
	 
	 if (check){
    	$('#email' + "_ok").show();
    	$('#email' + "_error").hide();
	 }
	 else{
    	$('#email' + "_ok").hide();
    	$('#email' + "_error").show();
	 }	
}


function isNumeric(sText){
	if (!sText) return false;
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++){ 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1){
         IsNumber = false;
      }
   }
   return IsNumber;
   
}



function load_options_post(id, url, params){
	var selected = $("#"+id).val();
		
	$.post(url, {"query[]": params}, function(data){

		$("#"+id + " option").each(function(){
			$(this).remove();
		});
	
		$.each(data, function(i,item){
			var sel = false;

			if (in_array(item.value, selected) || item.selected){
				sel = true;
			}
			
			var newoption = new Option(item.name, item.value, sel, sel);
			document.getElementById(id).options[document.getElementById(id).options.length] = newoption;
		});
	}, "json");	
}
 
    
function fade_out(div, seconds){
    window.setTimeout(function(){$("#"+div).fadeOut();}, seconds * 1000);
}


function init_direct_edit_input(){
    //console.log("init input");    
}

function init_direct_edit_textarea(){
    //console.log("init textarea");
}

function init_direct_edit_select(){
    
}

function init_direct_edit_checkbox(){
    $("#ppm_direct_edit_content").click(function(){
        if(!$(this).attr("checked")){
            $(this).val(0);
        }
        else{
            $(this).val(1);
        } 
    });
}

function init_direct_edit_media(){
    
    $mp_album_id = $("#mp_album_id").val();
    
    $("#mp_upload").html5_upload({
        url: '../../modules/ajax.php',
        additionalData: {"function":"mediapool_upload", 'phpclass': 'js_wysiwyg', "album_id":$mp_album_id, "item_id":"", "script_id":""},
        sendBoundary: window.FormData || $.browser.mozilla,
        onStart: function(event, total) {

            //check possible elements, not asynchron!
            var elements_left = "";  
            $.ajax({
            url:    '../../modules/ajax.php',
            success: function(result) {
                elements_left = result;
              },
              async:   false,
              type:   "POST",
              data: "function=get_elements_left&phpclass=js_wysiwyg&album_id="+$mp_album_id,
            });     
            
        
            if (total > elements_left) alert("too much");
            else{
                $("#progress_report").show();
                $("#progress_report_bar_container").css("border", "1px solid green");                    
                return true;
            }
        },
        setName: function(text) {
            $("#progress_report_name").text(text);
        },
        setStatus: function(text) {
            $("#progress_report_status").text(text);
        },
        setProgress: function(val) {
            $("#progress_report_bar").css('width', Math.ceil(val*100)+"%");
        },
        onFinish: function(val) {
            /*$("#progress_report").slideUp();*/
            //init_direct_edit_media();
            get_album_elements($("#mp_album_id").val());
        },
        onFinishOne: function(event, response, name, number, total) {
            $("#mp_album_id").val(response);
            get_album_elements($("#mp_album_id").val());
        }
    });  
    
    get_album_elements($("#mp_album_id").val());  

}

function init_direct_edit_list(){
    
}

function init_direct_edit_mediaslideshow(){
    init_direct_edit_media();
}

function init_direct_edit_module(){
    
}


//element editor of an album
function get_album_elements(album_id){
    //alert(album_id);
    //$("#progress_report_name").html("");
    //$("#progress_report").hide();
    
    
    $(".mp_album_elements").html(album_id);
    
    //console.log(selected_album_index);
    $.post("../../modules/ajax.php", { 'function': 'get_album_elements', 'phpclass': 'js_wysiwyg', 'album_id':album_id}, function(answer){
        $(".mp_album_elements").html(answer.html);
        
        upload_button(answer.disable_uploads);
        

        
        $(".mp_element").click(function(){
            //console.log($('#ppm_direct_edit_script_id').val());
            if ($('#ppm_direct_edit_type').val() == "media"){
                $(".mp_element").removeClass("sel");
                $(this).addClass("sel");

                $.post("../../modules/ajax.php", { 'function': 'set_active_element', 'phpclass': 'js_wysiwyg', 'element_id':$(this).attr("element_id")}, function(result){
                    if (result.status != "ok") alert("fail");
                },"json");                
            }
            else if($('#ppm_direct_edit_type').val() == "mediaslideshow"){
                //$(".mp_element").removeClass("sel");
                $(this).toggleClass("sel");

                $.post("../../modules/ajax.php", { 'function': 'toggle_active_element', 'phpclass': 'js_wysiwyg', 'element_id':$(this).attr("element_id")}, function(result){
                    if (result.status != "ok") alert("fail");
                },"json");
                
            }
            //console.log($('#ppm_direct_edit_script_id').val());
            


        });
        
        $( ".mp_elementlist" ).sortable({
            stop: function(event, ui){
                $.post("../../modules/ajax.php", { 'function': 'save_element_sorting', 'phpclass': 'js_wysiwyg', 'album_id': album_id, 'elements':$(this).sortable("toArray")}, function(status){
                   if (status != "ok") alert("failed");
                });                
//                mp_save_album();
            },
            placeholder: 'ui-state-default mp_element mp_sortable_placeholder'
        }).disableSelection();
   
   
        $( ".mp_options .delete" ).click(function(){
            delete_album_element($(this).attr("element_id"));
        });
        
        $( ".mp_options .info" ).click(function(){
             show_album_element_info_dialog($(this).attr("element_id"));
        });
                
        $( ".mp_options .preview" ).click(function(){
             show_album_element_preview_dialog($(this).attr("element_id"));
        });

        $( ".mp_options .right_90" ).click(function(){
            $("#album_element_"+ $(this).attr("element_id") + " div.mp_picture").html("<br /><br />"+$("#ajax_loader").html());
            $.post("../../modules/ajax.php", { 'function': 'rotate_image', 'phpclass': 'js_wysiwyg', 'element_id':$(this).attr("element_id"), "degrees":90 }, function(result){
                $("#album_element_"+ result.element_id + " div.mp_picture").html('<img height="95%" border="1" src="'+result.src+'">');
            },"json");
        });
        
        $( ".mp_options .left_90" ).click(function(){
            $("#album_element_"+ $(this).attr("element_id") + " div.mp_picture").html("<br /><br />"+$("#ajax_loader").html());
            $.post("../../modules/ajax.php", { 'function': 'rotate_image', 'phpclass': 'js_wysiwyg', 'element_id':$(this).attr("element_id"), "degrees":-90 }, function(result){
                $("#album_element_"+ result.element_id + " div.mp_picture").html('<img height="95%" border="1" src="'+result.src+'">');
            },"json");
        });        


        
        //return answer.disable_uploads;
        
/*        
        mp_bind_buttons();
        
        $(".mp_element").click(function(){
            $(".mp_element").removeClass("sel");
            $(this).addClass("sel");
        });
        
        $( ".mp_elementlist" ).sortable({
            stop: function(event, ui){
                mp_save_album();
            },
            placeholder: 'ui-state-default mp_element mp_sortable_placeholder'
        }).disableSelection();

        var $tabs = $( "#mp_albumlist" ).tabs({selected: selected_album_index});
        
        var $tab_items = $( "ul:first li", $tabs ).droppable({
            accept: ".connectedSortable li",
            
            hoverClass: "ui-state-hover",
            drop: function( event, ui ) {
                var $item = $( this );
                var $list = $( $item.find( "a" ).attr( "href" ) )
                    .find( ".connectedSortable" );

                ui.draggable.hide( "slow", function() {
                    $tabs.tabs( "select", $tab_items.index( $item ) );
                    $( this ).appendTo( $list ).show( "slow" , function(){
                        
                        var target_album_id = $(event.target).attr("album_id");
                        var element_id = $(this).attr("element_id");
                        mp_move_element(element_id, target_album_id);
                    });
                });
                
            }
        }); 
        
        
        
        $( ".mp_options .delete" ).click(function(){
            delete_album_element($(this).attr("element_id"));
        });
        
        $( ".mp_options .info" ).click(function(){
             show_album_element_info_dialog($(this).attr("element_id"));
        });
                
        $( ".mp_options .preview" ).click(function(){
             show_album_element_preview_dialog($(this).attr("element_id"));
        });

        $( ".mp_options .right_90" ).click(function(){
            $("#album_element_"+ $(this).attr("element_id") + " div.mp_picture").html("<br /><br />"+$("#ajax_loader").html());
            $.post("../../modules/ajax.php", { 'function': 'rotate_image', 'phpclass': 'js_wysiwyg', 'element_id':$(this).attr("element_id"), "degrees":90 }, function(result){
                $("#album_element_"+ result.element_id + " div.mp_picture").html('<img height="95%" border="1" src="'+result.src+'">');
            },"json");
        });
        
        $( ".mp_options .left_90" ).click(function(){
            $("#album_element_"+ $(this).attr("element_id") + " div.mp_picture").html("<br /><br />"+$("#ajax_loader").html());
            $.post("../../modules/ajax.php", { 'function': 'rotate_image', 'phpclass': 'js_wysiwyg', 'element_id':$(this).attr("element_id"), "degrees":-90 }, function(result){
                $("#album_element_"+ result.element_id + " div.mp_picture").html('<img height="95%" border="1" src="'+result.src+'">');
            },"json");
        });
        */
        
    }, "json");    
}


function upload_button(disable){
    if (disable){ 
        $("#mp_upload").hide();
        //$("#mp_upload").html5_upload['continue_after_abort'] = false;
        //$("#mp_upload").html5_upload['xhr'].abort();
    }
    else $("#mp_upload").show();
    
}
