// Include JQuery Plugins that are used in almost every project 
document.write("<script type='text/javascript' src='http://fanclub.dfb.de/dfb-toolbox/javascripts/jquery.swfobject.1-1-1.min.js'></script>");
document.write("<script type='text/javascript' src='http://fanclub.dfb.de/dfb-toolbox/javascripts/jquery.slider.js'></script>");

// todo: diese konstante an zentraler stelle definieren
window.groupfire_base_uri = 'http://fanclub.groupfire.net';

function musik_schalter(trigger) {
  $.get("http://fanclub.dfb.de/fileadmin/phpscripts/musiccookie.php", { aus: (!trigger ? 1 : 0)});
}

//jQuery.fn.exists = function() { return Boolean(jQuery(this).length > 0);}

$(document).ready(function() {
	
	$('.groupfire .message .content a').live('click', function () {
    if ($(this).attr('href').indexOf('http://') == 0) {
      $(this).attr('target', '_blank');
    }
  });
	
  // Fanshop Link ueberschreiben
	$('a[href=http://www.dfb-fanshop.de]').attr('target', '_blank');
	
  // Profil Link aus Groupfire ueberschreiben
	$('#MainColumn .groupfire .profile .photo a.img').attr('href', 'http://fanclub.dfb.de/index.php?id=519027');
	
	// Breadcrumb für MitgliederÜbersicht ausblenden
	$('.breadcrumbs a[href="/people"]').hide();
	
	$('.fcn_newest_photos li img, .fcn_newest_videos li img, .fanupdates_box li img').each(function(index, element) {
    var element_title = $(element).attr('title');
    $(element).parents('a').attr('title', '');
    $(element).attr('title', '').attr('alt', '').qtip({
      content: {
         text: element_title
      },
      show: { effect: { type: 'slide' } },
      /*position: {
         corner: {
            tooltip: 'topMiddle',
            target: 'bottomMiddle'
         },
         adjust: {
            resize: true,
            scroll: true
         }
      },*/
      style: {
        name: 'dark',
        fontSize: 11,
        tip: true,
        border: {
          radius: 5
        }
      }          
   });
  });
  
  $(".fancy_i2plus").fancybox({
 		  'titleShow'     	: false,
 			'width'				: 822,
 			'height'			: 480,
 			'transitionIn'		: 'elastic',
 			'transitionOut'		: 'elastic',
 			'type'				: 'iframe'
 		});

	$(".fancy_trailer").fancybox({
	  onStart : function(){
	    $('#FanclubTrailer').show();
	  },
	  onClosed : function(){
	    $('#FanclubTrailer').hide();
	  }
	});
	
	$(".fancy_board").fancybox({
		  'titleShow'     	: false,
			'width'				: 640,
			'height'			: 720,
			'transitionIn'		: 'elastic',
			'transitionOut'		: 'elastic',
			'type'				: 'iframe'
		});	
		
	$(".fancy_eventim").fancybox({
		    'titleShow'     	: false,
			'width'				: 970,
			'height'			: 500,
			'transitionIn'		: 'elastic',
			'transitionOut'		: 'elastic',
			'type'				: 'iframe'
		});		

		$(".fancy_tippspiel").fancybox({
			    'titleShow'     	: false,
				'width'				: 822,
				'height'			: 680,
				'transitionIn'		: 'elastic',
				'transitionOut'		: 'elastic',
				'type'				: 'iframe'
			});
      
  if ($('#gf_ajax_profile_box').length > 0) {
    
    // wenn wir auf groupfire sind reichen relative pfade
    if (window.location.protocol + '//' + window.location.host == window.groupfire_base_uri) {
      status_json_uri = '/status.json';
      message_update_uri = '/messages';
    // auf typo3 linken wir auf die jeweiligen proxies
    } else {
      status_json_uri = '/dfb-toolbox/phpscripts/status.json.php';
      message_update_uri = '/dfb-toolbox/phpscripts/message.update.php';
    }
    logout_link = window.groupfire_base_uri + '/logout?return_to=http://fanclub.dfb.de/index.php?id=519024%26no_cache=1%26logout=1';
    profile_edit_link = 'http://fanclub.dfb.de/index.php?id=519027';
    $.ajaxSetup({ cache: false });
    $.getJSON(status_json_uri, null, function(json_response){
     var profile_box_template = '<div class="right_column_box">  <h1>    Mein Fan Club  </h1><img width="81" height="81" class="profile_box" alt="{user.login}" src="{groupfire_base_uri}{user.person.photo_url_grid}">  <div class="mainaction_wrapper">    <strong>{user.display_name}</strong><ul style="margin: 0pt;" class="profile_mainactions">      <li class="profile_icons pi_profile">        <a href="{groupfire_base_uri}/users/{user.id}">Mein Profil</a>      </li>      <li class="profile_icons pi_settings">        <a id="profile_links_toggler" href="javascript:;">Einstellungen</a>        <ul class="profile_links profile_menu" style="display: none;">          <li>            <a class="fancy_i2plus" href="https://62.153.106.230/fcnrel/cssadr/adrlogin.php">Stammdaten</a>          </li>          <li>            <a href="{profile_edit_link}">Profilbild &amp; Freigaben</a>          </li>          <li>            <a href="{groupfire_base_uri}/users/{user.id}/custom">Profilfragen</a>          </li>  </ul>      </li>      <li class="profile_icons pi_logout">        <a class="" href="{logout_link}">Abmelden</a>      </li>    </ul>  </div>  <div class="profile_box_state">    <form action="{groupfire_base_uri}/messages" class="new_message" id="new_message" method="post" name="new_message">      <p title="Dies ist Deine Status-Meldung. Sage anderen Fans, was Dich gerade beschäftigt." class="status_info">        <textarea id="profile_box_status_input" maxlength="140" name="message[title]" size="140" style="height: 16px;">{user.status_message}</textarea>      </p><input type="hidden" id="message_space_id" name="message[space_id]" value="{user.space_id}">    </form>  </div>  <p id="status_loading" style="margin: -10px 10px 5px; display: none; font-weight: bold; color: rgb(204, 0, 0);">    Status-Speicherung erfolgt...  </p>  <p id="status_feedback" style="margin: -10px 10px 5px; display: none; font-weight: bold; color: rgb(204, 0, 0);">    Dein Status wurde gespeichert.  </p> <h2 class="profile_legend pi_messages">    Mitteilungen  </h2>  <ul class="profile_actionlist">    <li>      <a href="{groupfire_base_uri}/messages?filter=personal">Posteingang (<strong>{user.count_unread_personal_messages}</strong>)</a>    </li>    <li>      <a href="{groupfire_base_uri}/messages?filter=sent">Postausgang</a>    </li>  </ul>  <h2 class="profile_legend pi_friends">    Mitglieder  </h2>  <ul class="profile_actionlist">    <li>      <a href="{groupfire_base_uri}/users/{user.id}/friendships">Liste meiner Freunde {user.count_open_friendships}</a>    </li>  <li>      <a href="{groupfire_base_uri}/users/{user.id}/visits">Besucher meines Profils</a>    </li></ul></div>';
     var online_users_block_template = '<h2 style="padding-bottom: 10px;" class="profile_legend profile_separator">{online_users_info}</h2>';
     var online_users_item_template = '<a style="border: 1px solid rgb(238, 238, 238); float: left; margin-right: 3px;" href="{groupfire_base_uri}/users/{id}"><img width="32" height="32" title="{display_name}" src="{groupfire_base_uri}{photo_url_icon}" alt="{display_name}"></a>';
     //json_response = {"groupfire_base_uri":window.groupfire_base_uri, "user":{"person":{"foreign_key":"","photo_url_grid":"/contact_photos/000/013/755/johnny-depp-jack-sparrows_grid.jpg","photo_file_size":160527,"created_at":"2010-04-15T14:29:27+02:00","title":"jack","remark":"","job_title":"","updated_at":"2010-06-01T20:17:51+02:00","photo_file_name":"johnny-depp-jack-sparrows.jpg","deleted_at":null,"photo_content_type":"image/jpeg","locker_id":null,"account_id":2,"id":13755,"creator_id":66,"attached_to_type":null,"updater_id":66,"attached_to_id":null,"last_name":"daJava","company_id":null,"birthday":null,"locked_at":null,"description":"","honory_title":"","first_name":"Jack","external_data":null},"count_unread_personal_messages":0,"location":null,"last_request_at":"2010-11-04T13:00:11+01:00","created_at":"2010-04-15T14:29:57+02:00","jabber_activated":null,"updated_at":"2010-11-04T13:00:12+01:00","deleted_at":null,"account_id":2,"id":8221,"hide_profile_visits":null,"current_login_ip":"127.0.0.1","creator_id":66,"valid_from":null,"updater_id":66,"professional_interests":null,"disable_notifications":null,"current_login_at":"2010-11-04T11:53:15+01:00","valid_until":null,"person_id":13755,"login_count":434,"jabber_address":null,"time_zone":"Berlin","locale":"de-DE","last_login_ip":"127.0.0.1","display_name":"jack","description":null,"login":"jack","last_login_at":"2010-11-02T10:49:27+01:00","terms_of_service_accepted_at":null,"personal_interests":null,"email":"mk@katzer-neumann.de"}};
     //json_response = {"online_users":[{"display_name":"Wolfgang Xander","photo_url_icon":"/contact_photos/272/755/295/Wolfgang_Xander_icon.jpg","id":272755295}],"user":{"space_id":272755295,"login":"wolfgang","display_name":"Wolfgang Xander","description":null,"count_unread_personal_messages":2,"location":null,"status_message":"Hallo von Wolfgang an alle","id":272755295,"person":{"title":"Wolfgang Xander","photo_url_grid":"/contact_photos/272/755/295/Wolfgang_Xander_grid.jpg","last_name":"Xander","id":272755295,"first_name":"Wolfgang"},"email":"ok@yum.de"}};
     
     if(json_response) {
       json_response.groupfire_base_uri = window.groupfire_base_uri;
       json_response.online_users_info = 'Derzeit sind unter anderem diese Benutzer online:';
       if (json_response.online_users_count > 0) {
         json_response.online_users_info = 'Derzeit ist ein weiterer Benutzer online:';
       }
       if (json_response.online_users_count > 1) {
         json_response.online_users_info = 'Derzeit sind ' + json_response.online_users_count + ' Benutzer online, darunter auch:';
       }
       json_response.logout_link = logout_link;
       json_response.profile_edit_link = profile_edit_link;
       
       if (json_response.user.count_open_friendships > 0) {
         json_response.user.count_open_friendships = '(<strong>'+json_response.user.count_open_friendships+'</strong>)';
       } else {
         json_response.user.count_open_friendships = '';
       }
       
       // haupttemplate ins dom integrieren
       $('#gf_ajax_profile_box').html($.nano(profile_box_template, json_response));

       if (json_response.user.groups.length > 0) {
           current_groups = new Array();
           for (var i = 0; i < json_response.user.groups.length; i++) {
             current_groups.push(json_response.user.groups[i].id);
           }
           admin_links = '';
           if($.inArray(12, current_groups) != -1 || $.inArray(17, current_groups) != -1 || $.inArray(16, current_groups) != -1 || $.inArray(13, current_groups) != -1) {
              admin_links += '<h2 class="profile_legend pi_friends">Spezielle Foren</h2>';
              admin_links += '<ul class="profile_actionlist">';
            }

          // auf Gruppe Fanclub-Betreuer prüfen => GroupID = 12
            if($.inArray(12, current_groups) != -1 || $.inArray(17, current_groups) != -1 || $.inArray(16, current_groups) != -1) {
                admin_links += '<li><a href="{groupfire_base_uri}/categories/9627" class="profile_special_link">Fan-Club Betreuer Forum (Extranet)</a></li>';    
            }

          // auf Gruppe Website intern prüfen => GroupID = 16
            if($.inArray(16, current_groups) != -1) {
              admin_links += '<li><a href="{groupfire_base_uri}/categories/9659" class="profile_special_link">Internes Forum zur Website</a></li>';
              admin_links += '<li><a href="http://fanclub.groupfire.net/messages/440162" class="profile_special_link">Interne Kontaktliste</a></li>';
            }

          // auf Gruppe Choreo-Helfer prüfen => GroupID = 13
            if($.inArray(13, current_groups) != -1) {
              admin_links += '<li><a href="{groupfire_base_uri}/categories/9640" class="profile_special_link">Choreo-Helfer Forum</a></li>';
            }

            if($.inArray(12, current_groups) != -1 || $.inArray(17, current_groups) != -1 || $.inArray(16, current_groups) != -1) { 
              admin_links += '</ul>';
            }

            if($.inArray(14, current_groups) != -1 || $.inArray(15, current_groups) != -1 || $.inArray(17, current_groups) != -1) {
              admin_links += '<h2 class="profile_legend pi_admin"><a href="javascript:;" onclick="$(\'ul.admin_links\').toggle();">Administration</a></h2>';
              admin_links += '<ul class="profile_actionlist admin_links" style="display:none;">';
            }

          // auf Gruppe Redaktion prüfen => GroupID = 17
            if($.inArray(17, current_groups) != -1) {
            admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/articles/extended/" target="_blank">Redaktionssystem</a></li>';
            admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/poll/?_sort=-date_begin&_action=list" target="_blank">Umfragen</a></li>';
            admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/fantastic/lottery.php"  target="_blank">Fan-tastic Moments</a></li>';
            admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/gewinnspiele/lottery.php"  target="_blank">Gewinnspiele</a></li>';
            admin_links += '<li><a href="{groupfire_base_uri}/categories/9501">Bildergalerien</a></li>';
            }

          // auf Gruppe Fan-Treff Moderatoren prüfen => GroupID = 14
            if($.inArray(14, current_groups) != -1) {
              admin_links += '<li><a href="{groupfire_base_uri}/spaces/8594/reports" class="profile_special_link">Missbrauchsmeldungen</a></li>';
            }

          // auf Gruppe Fan Club-Admins prüfen => GroupID = 15
            if($.inArray(15, current_groups) != -1) {
              admin_links += '<li><a href="http://fanclubarchiv.katzer-neumann.de/newsletter/admin" target="_blank" class="profile_special_link">Newsletter-System</a></li>';
              admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/bets/bets_categories.php" target="_blank">Tippspiel: Kategorien</a></li>';
              admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/bets/bets_matches.php" target="_blank">Tippspiel: Spiele</a></li>';
              admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/bets/bets_specials.php" target="_blank">Tippspiel: Spezial Tipps</a></li>';
              admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/bets/_calculate.php" target="_blank">Tippspiel: Punkte berechnen</a></li>';
              admin_links += '<li><a href="http://fanclub.dfb.de/fileadmin/phpscripts/admin/users_board/?_sort=-created_at" target="_blank">Mitgliederdaten</a></li>';
            }

            if($.inArray(14, current_groups) != -1 || $.inArray(15, current_groups) != -1 || $.inArray(17, current_groups) != -1) {
              admin_links += '</ul><br />';
            }
            $('#gf_ajax_profile_box').append($.nano(admin_links, json_response));
         }

       
       var online_user_list = '';
       if (json_response.online_users.length > 0) {
         for (var i = 0; i < json_response.online_users.length; i++) {
           json_response.online_users[i].groupfire_base_uri = groupfire_base_uri;
           online_user_list += $.nano(online_users_item_template, json_response.online_users[i]);
         }
         online_user_list = $.nano(online_users_block_template, json_response) + online_user_list + '<br style="clear: both;">';
         $('#gf_ajax_profile_box').append(online_user_list);
       }
       $('#status_message_explanation').html('Sage anderen Fans, was Dich gerade besch&auml;ftigt. Speichere mit der Return-Taste.<br />Diese Nachricht kann von allen Mitgliedern in Deinem Profil gelesen werden!');
       $('ul.profile_links').hide();
       
       // zeige technical updates popover an, wenn die var "has_technical_updates" 1 ist
       if (json_response.has_technical_updates == 1) {
         $.fancybox("http://fanclub.dfb.de/fileadmin/phpscripts/fanclub_updates.php", {
         	'width'				    : 822,
         	'height'			    : 480,
         	'transitionIn'		: 'elastic',
         	'transitionOut'		: 'elastic',
         	'type'				    : 'iframe',
         	'onClosed'		    : function() {
             $.ajax({
               type          : "POST",
               cache         : false,
               url           : "http://fanclub.dfb.de/fileadmin/phpscripts/fanclub_updates_recognized.php",
               data          : "user_id=" + json_response.user.id
             });
         	}
         });
       }
       
       $(".fancy_i2plus").fancybox({
     		  'titleShow'     	: false,
     			'width'				: 822,
     			'height'			: 480,
     			'transitionIn'		: 'elastic',
     			'transitionOut'		: 'elastic',
     			'type'				: 'iframe'
     		});	
       
       $('.status_info').attr('title', '').qtip({
             content: {
                text: 'Deine Status-Meldung: Sage anderen Fans, was Dich gerade besch&auml;ftigt. Tippe direkt in die Sprechblase und speichere mit der Return-Taste. Diese Nachricht kann von allen Mitgliedern in Deinem Profil gelesen werden!'
             },
             show: { effect: { type: 'slide' } },
             position: {
                corner: {
                   tooltip: 'topMiddle',
                   target: 'bottomMiddle'
                },
                adjust: {
                   resize: true,
                   scroll: true
                }
             },
             style: {
               name: 'dark',
               fontSize: 11,
               tip: true,
               border: {
                 radius: 5
               }
             }
          });
       
       // event handling für statusmessagebox connecten
       $("#profile_links_toggler").click(function() { $('ul.profile_links').toggle(); }); 
       $("#profile_box_status_input").css("height", $("#profile_box_status_input")[0].scrollHeight);
       $("#profile_box_status_input").focus(function(event) { this.oldvalue = this.value; this.select(); event.preventDefault(); return false; });
       $("#profile_box_status_input").blur(function(event) {
         if (this.oldvalue != this.value) {
           this.value = this.oldvalue;
         }
       });
       $("#profile_box_status_input").keydown(function(event) {
       if (event.keyCode == 13) {
         if (this.oldvalue != this.value) {
           this.oldvalue = this.value;
           $("#status_loading").css("display", "block");
           $.post(message_update_uri, {"message[space_id]" : $("#message_space_id").val(), "message[title]" : $("#profile_box_status_input").val()},
             function() {
               $("#profile_box_status_input").css("height" , 16);
               $("#profile_box_status_input").css("height", $("#profile_box_status_input")[0].scrollHeight);
               $("#status_loading").css("display", "none");
               $("#status_feedback").css("display", "block").fadeOut(2000);
             }
           );
         }
         $("#profile_box_status_input").blur();
       } else {
         if ($("#profile_box_status_input").val().length <= 140 || event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9 || (event.keyCode >= 37 && event.keyCode <= 40)) {
           $("#profile_box_status_input").css("height" , 16);
           $("#profile_box_status_input").css("height", $("#profile_box_status_input")[0].scrollHeight);
         } else {
           event.preventDefault();
         }
       }
     });
    } 
    /*else {
      document.location.href = 'http://fanclub.dfb.de/index.php?id=519024&no_cache=1&logout=1&autologgedout=1';
    }*/
    });
  }
});

(function($){
  $.nano = function(template, data){
    return template.replace(/\{([\w\.]*)}/g, function(str, key){
      var keys = key.split("."), value = data[keys.shift()];
      $.each(keys, function(){ value = value[this] });
      return value;
    });
  }
})(jQuery);

