$(document).ready(function() {

    $.history.init(loadContent);

    // Initiate Facebook
    $.ajax({
          type:'GET',
          dataType: 'script',
          cache: true,
          url: document.location.protocol + '//connect.facebook.net/de_DE/all.js',
          success: function(){
                    window.fbAsyncInit = function() {
                        FB.init({appId: '135263433189341', status: true, cookie: true, xfbml: true});
                        $.ajax({
                          type:'GET',
                          cache: true,
                          dataType: 'script',
                          url: 'http://cdn.niedersteiner.de/script/fbObjectValidationV4.js'
                        });
                    };
                  }
    });

    // Google Analytics
    $.ga.load("UA-736311-1",function(pageTracker) {
                                     pageTracker._setDomainName("www.niedersteiner.de");
                                     pageTracker._trackPageview();
    });

    // Das Theme für die prettyPhoto Library initialisieren
    $.fn.prettyPhoto({'theme': 'dark_rounded'});

    /** Video in der Box **/
    $("a[data-type^=prettyVideo]").livequery("click",function() {
        $.prettyPhoto.open($(this).attr("href"),$(this).attr("title"),$(this).attr("data-description"));
        return false;
    });

    /**
    Wird ein Kleines Thumbnail angeklickt, zuerst das angeklickte Element in die Arrays legen.
    Dann alle sichtbaren Thumbs durchgehen. wenn das Thumb noch nicht im Array ist, rein damit.
    **/
    $("a[data-type^=prettyPhoto]").livequery("click",function() {
        var api_images=new Array();
        var api_titles=new Array();
        var api_descriptions=new Array();

        api_images.push($(this).attr("href"));
        api_titles.push($(this).find('img').attr("alt"));
        api_descriptions.push($(this).find('img').attr("data-description"));

        $('.thumbnailImageContainerFotografie').each(function(index) {
                                                        if($(this).css('opacity')!=0){
                                                            if(jQuery.inArray($(this).find('a').attr("href"), api_images)==-1){ // nicht im Array
                                                                api_images.push($(this).find('a').attr("href"));
                                                                api_titles.push($(this).find('img').attr("alt"));
                                                                api_descriptions.push($(this).find('img').attr("data-description"));
                                                            }
                                                        }
        });
        $.prettyPhoto.open(api_images,api_titles,api_descriptions);
        return false;
    });


    /* handler Link wird angeklickt */
    $('.actionLink').click(function(e) {
        var url=$(this).attr("data-name");
        url = url.replace(/^.*#/, '');
        $.history.load(url);
        return false;
    });

    /* Asynchrner Homelink */
    $('.homeLink').click(function(e) {
        var url='';
        $.history.load(url);
        return false;
    });


    /* Content Laden und die nötigen Divs anpassen */
    function loadContent(hash) {
         $.ga.load("UA-736311-1",function(pageTracker) {
                                          pageTracker._setDomainName("www.niedersteiner.de");
                                          pageTracker._trackPageview(hash);
        });
        if(hash != "") {
            if(navigator.userAgent.indexOf('MSIE') == -1){
                $('#contentContainer').switchClass('content_inactive',
                                                   'content_active',
                                                   400,
                                                   function(){
                                                       $('.level1Link').hide("fade",350, function(){
                                                                                      $('.homeLink').show("fade",400, function(){
                                                                                                                  $('#contentContainer').html('<div class=\"loadingAnimation\"></div>');
                                                                                                                  $('#contentContainer').load('/dynamic/getDynamicContent.php',{p:hash});
                                                                                                                  $.ajax('/dynamic/loadPageTitle.php',
                                                                                                                      {
                                                                                                                          data: {content:hash},
                                                                                                                          dataType: "html",
                                                                                                                          success: function(data){
                                                                                                                                       if(top.window.document.title != data){
                                                                                                                                           top.window.document.title = data;
                                                                                                                                       }
                                                                                                                                   }
                                                                                                                      }
                                                                                                                 );
                                                                                                               }
                                                                                      );
                                                                                  }
                                                       );
                                                   }
    
                );
            }
            else{ 
                //$('#contentContainer').switchClass('content_inactive','content_active');
                $("#contentContainer").removeClass("content_inactive").addClass("content_active");
                $('.level1Link').hide("fade",350, function(){
                    $('.homeLink').show("fade",400, function(){
                        $('#contentContainer').html('<div class=\"loadingAnimation\"></div>');
                        $('#contentContainer').load('/dynamic/getDynamicContent.php',{p:hash});
                        $.ajax('/dynamic/loadPageTitle.php',
                          {
                              data: {content:hash},
                              dataType: "html",
                              success: function(data){
                                           if(top.window.document.title != data){
                                               top.window.document.title = data;
                                           }
                                       }
                          }
                        );
                   });
                });
                  
            }
        }
        else{
            if(navigator.userAgent.indexOf('MSIE') == -1){
                $('#contentContainer').html('');
                $('#contentContainer').switchClass('content_active','content_inactive',400,function(){
                   $('.homeLink').hide("fade",200,function(){
                                               $('.level1Link').show("fade",350);
                                           }
                   );
               });
            }
            else{
                $('#contentContainer').html('');
                $("#contentContainer").removeClass("content_active").addClass("content_inactive");
                $('.homeLink').hide("fade",200,function(){
                    $('.level1Link').show("fade",350);
                });
            }
        }
    }

    /* Mouseover Effekt kleine thumbs */
    $('.transparentThumbnail').livequery('mouseover',function(e) {
        //$(this).css("opacity",1);
        $(this).css("border",'1px solid #da821d');

    });

    /* Reset Mouseover kleine Thumbs */
    $('.transparentThumbnail').livequery('mouseout',function(e) {
        //$(this).css("opacity",0.4);
        $(this).css("border",'1px solid #999');
    });

    /* Blende alle Thumbs aus die nicht zur gewählten Kategorie gehören*/
    /*
    $('.doThumnailHide').livequery('click',function(e) {
        $('.thumbnailImageContainerFotografie').each(function(index) {
                                                        $(this).show();
        });
        var showClass=$(this).attr("data-name");
        $('.thumbnailImageContainerFotografie').each(function(index) {
                                                        if(!$(this).hasClass(showClass)){
                                                            $(this).hide();
                                                        }
        });
        return false;
    }); 
    */
    $('.doThumnailHide').livequery('click',function(e) {
        $('.thumbnailContainerFotografie').html('<div class=\"loadingAnimation\"></div>');
        $('.thumbnailContainerFotografie').load('/dynamic/fotografie_loadThumbsByCat.php',{p:$(this).attr("data-name")});
        return false;
    });
    

    /* Meister */
    $('#loginSubmit').livequery('click',function(e) {
        $.ajax('/dynamic/login.php',
              {
                  data: {u:$('#username').val(),p:$('#password').val()},
                  cache: false,
                  dataType: "html",
                  beforeSend: function( xhr ) {
                    $('#loginResult').html('<div class=\"loadingAnimation\"></div>');
                  },
                  success: function(data){
                            $('#loginResult').html(data);
                          }
              }
         );
        return false;
    });

    $('.adminLink').livequery('click',function(e) {
        $.ajax('/dynamic/getAdminContent.php',
              {
                  data: {t: $(this).attr("data-name")},
                  cache: false,
                  dataType: "html",
                  timeout: 15000,
                  beforeSend: function( xhr ) {
                    $('#admin_area').html('<div class=\"loadingAnimation\"></div>');
                  },
                  error: function(){
                            alert("an error occured");
                         },
                  success: function(data){
                            $('#admin_area').html(data);

                            if($('#file-uploader').length != 0){
                                var uploader = new qq.FileUploader({
                                    element: document.getElementById('file-uploader'),
                                    action: '/dynamic/upload.php',
                                    allowedExtensions: ['jpg'],
                                    debug: true
                                });
                            }
                          }
              }
         );
        return false;
    });

    $('#fingerWegAnimContainer').livequery('mouseover',function(e) {
        //$('#fingerWegAnim').css('background-image','url("http://cdn.niedersteiner.de/UN_fingerweg.gif")');
        $('#fingerWegAnim').css('display','block');
    });

    $('#fingerWegAnimContainer').livequery('mouseout',function(e) {
        //$('#fingerWegAnim').css('background-image','url("http://cdn.niedersteiner.de/transparent_1_1.png")');
        $('#fingerWegAnim').css('display','none');
    });

    $('.adminAction').livequery('click',function(e) {
        var type=$(this).attr("data-action-type");
        var id=$(this).attr("data-id");
        var value1=$("#value_1").val();
        var value2=$("#value_2").val();
        var content=$(this).attr("data-type");
        $.ajax('/dynamic/doAdminAction.php',
              {
                  data: {t: type, id: id, content: content, val1: value1, val2: value2},
                  cache: false,
                  timeout: 15000,
                  dataType: "html",
                  error: function(){
                            alert("an error occured");
                         },
                  success: function(data){
                               if(type=="delete"){
                                   if(data=="OK"){
                                       $('#'+id).hide("fade",200);
                                   }
                                   else{
                                       alert(data);
                                   }
                               }
                               if(type=="insert"){
                                   var indexOfError=data.indexOf( "errorerror" );
                                   if( indexOfError == -1){
                                       $('#adminDataTable').append(data);
                                       $("#value_1").val()='';
                                       $("#value_2").val()='';
                                   }
                                   else{
                                       indexOfError+=10;
                                       alert(data.substr(indexOfError,data.length));
                                   }
                               }
                           }
              }
         );
         return false;
    });

    $('.adminActionSlotEnable').livequery('change',function(e) {
        var slotNo=$(this).attr("data-slotno");
        var type=$(this).attr("value");
        if(type=="off"){
            $('#slot_content_value_conatiner_'+slotNo).html('');
        }
        else{
            $.ajax('/dynamic/adminBlogSlotContentContainer.php',
                  {
                      data: {type: type, slot: slotNo},
                      cache: false,
                      dataType: "html",
                      success: function(data){
                                $('#slot_content_value_conatiner_'+slotNo).html(data);
                              }
                  }
             );
        }
    });



    $('.adminActionBlog').livequery('click',function(e) {
        $.ajax('/dynamic/doAdminActionBlog.php',
              {
                  data: {headline: $('#value_1').val(), text: $('#value_2').val(),
                         slot1: $("input:radio[name='slot_content_type_0']:checked").val(),
                         slot2: $("input:radio[name='slot_content_type_1']:checked").val(),
                         slot3: $("input:radio[name='slot_content_type_2']:checked").val(),
                         slotvalue1: $("#slot_content_value_0").val(),
                         slotvalue2: $("#slot_content_value_1").val(),
                         slotvalue3: $("#slot_content_value_2").val()
                  },
                  cache: false,
                  timeout: 15000,
                  dataType: "html",
                  error: function(){
                            alert("an error occured");
                         },
                  success: function(data){
                               if(data=="OK"){
                                   $('#activeBlogEntries').load('/dynamic/activeBlogEntries.php');
                               }
                               else{
                                   alert(data);
                               }
                           }
              }
         );
         return false;
    });

    $('.bridgeDeleteAction').livequery('click',function(e) {
        var folder=$(this).attr("data-value");
        if(confirm('Willst du ' + folder + ' zur Löschung eintragen?')){
            $.ajax('/dynamic/doAdminActionDeleteBridge.php',
                  {
                      data: {folder: folder},
                      cache: false,
                      timeout: 15000,
                      dataType: "html",
                      error: function(){
                                alert("an error occured");
                             },
                      success: function(data){
                                   $('#bridgeDeleteInsertResult').html(data);
                               }
                  }
             );
        }
         return false;
    });




    $('.updateMetaValues').livequery('blur',function(e) {
        var target='result_' + $(this).attr("data-type")+'_'+$(this).attr("data-page");
        $.ajax('/dynamic/doAdminActionMeta.php',
              {
                  data: {type: $(this).attr("data-type"),
                         value:$(this).attr("value"),
                         page: $(this).attr("data-page")
                  },
                  cache: false,
                  timeout: 15000,
                  dataType: "html",
                  error: function(){
                            alert("an error occured");
                         },
                  success: function(data){
                               $('#'+target).html(data);
                           }
              }
         );
         return false;
    });

    $('.deleteWerkelnBlogImage').livequery('click',function(e) {
        var image = $(this).attr("data-name");
        var md5=$.md5(image);
        $.ajax('/dynamic/deleteBlogImage.php',
              {
                  data: {file: image},
                  cache: false,
                  timeout: 15000,
                  dataType: "html",
                  error: function(){
                            alert("an error occured");
                         },
                  success: function(data){
                               if(data=="OK"){
                                   $('#'+$.md5(image)).hide("fade",200);
                               }
                               else{
                                   alert(data);
                               }
                           }
              }
         );
         return false;
    });
});


